EViews 14 Command Ref

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1273

EViews 14 Command and

Programming Reference
EViews 14 Command and Programming Reference
Copyright © 1994–2024 S&P Global Inc.
All Rights Reserved

This software product, including program code and manual, is copyrighted, and all rights are
reserved by S&P Global Inc. The distribution and sale of this product are intended for the use of
the original purchaser only. Except as permitted under the United States Copyright Act of 1976,
no part of this product may be reproduced or distributed in any form or by any means, or stored
in a database or retrieval system, without the prior written permission of IHS Global Inc.

Disclaimer
The authors and S&P Global Inc. assume no responsibility for any errors that may appear in this
manual or the EViews program. The user assumes all responsibility for the selection of the pro-
gram to achieve intended results, and for the installation, use, and results obtained from the pro-
gram.

Trademarks
EViews® is a registered trademark of S&P Global Inc. Windows, Excel, PowerPoint, and Access
are registered trademarks of Microsoft Corporation. PostScript is a trademark of Adobe Corpora-
tion. Bloomberg is a trademark of Bloomberg Finance L.P. All other product names mentioned in
this manual may be trademarks or registered trademarks of their respective companies.

Third Party Licenses


This section contains third party notices or additional terms and conditions applicable to certain
software technologies which may be used in one or more EViews products and/or services.
Please be sure to consult the individual product files, about box, and/or install or manual docu-
mentation for specific copyright notices and author attributions. Notices on this page are current
for EViews products released on or after October 1, 2017.
• diff template Library - Copyright © 2015 Tatsuhiko Kubo [email protected]. All
rights reserved.
• FFmpeg Library - FFmpeg is a trademark of Fabrice Bellard, originator of the FFmpeg
project.
• GZipHelper - Copyright © 1995-2002 Gao Dasheng [email protected].
• Java SE Runtime Environment v1.8.0_401 licensed under Oracle Binary Code License
Agreement.
• JDemetra+ v3 licensed under European Union Public License v1.2.
• jsonCPP Library - Copyright © 2007-2010 Baptiste Lepilleur and The JsonCPP Authors.
• openssl Library - Copyright © 1998-2016 The OpenSSL Project. All rights reserved.
• libcurl Library - Copyright © 1996-2013, Daniel Stenberg [email protected].
• libharu Library - Copyright © 2000-2006 Takeshi Kanno, Copyright © 2007-2009 Antony
Dovgal et all.
• libssh2 Library - Copyright © 2004-2007 Sara Golemon [email protected], Copyright ©
2005, 2006 Mikhail Gusarov [email protected], Copyright © 2006-2007 The
Written Word, Inc., Copyright © 2007 Eli Fant [email protected], Copyright © 2009 Daniel
Stenberg, Copyright © 2008, 2009 Simon Josefsson. All rights reserved.
• Meta Prophet 1.1.5 licensed under MIT license. Copyright (c) Facebook, Inc. and its affil-
iates.
• OpenXLSX Library Copyright © 2020, Kenneth Troldal Balslev All rights reserved.
• Python 3 licensed under Python Software Foundation License.
• rapidjson Library - Copyright © 2015 THL A29 Limited, a Tencent company, and Milo Yip.
• shapelib Library - Copyright © 1998 Frank Warmerdam.
• ssleay License - Copyright © 1995-1998 Eric Young ([email protected]) All rights
reserved.
• Tableau Data Extract API - Copyright © 2003-2017 Tableau and its licensors. All rights
reserved.
• Tramo/Seats - Copyright (c) 1996 Agustin Maravall and Victor Gomez. Windows version
developed by G. Caporello and A. Maravall (Bank of Spain)
• X11.2 and X12-ARIMA version 0.2.7 and X-13ARIMA-SEATS - Copyright (c) U.S. Census
Bureau.

zlib Data Compression Library - Copyright © 1995-2017 Jean-loup Gailly and Mark
Adler.Notices, terms and conditions pertaining to third party software are located at http://
www.eviews.com/thirdparty and incorporated by reference herein.

S&P Global Inc.


Telephone: (949) 856-3368
e-mail: [email protected]
web: www.eviews.com
June 24, 2024
Table of Contents

PREFACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
CHAPTER 1. OBJECT AND COMMAND BASICS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Command Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Using Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Object Declaration and Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Object Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Object Data Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Interactive Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Auxiliary Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

CHAPTER 2. WORKING WITH GRAPHS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33


Creating a Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Changing Graph Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Customizing a Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Labeling Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Printing Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Exporting Graphs to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Graph Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

CHAPTER 3. WORKING WITH TABLES AND SPREADSHEETS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57


Creating a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Assigning Table Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Customizing Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Labeling Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Printing Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Exporting Tables to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Customizing Spreadsheet Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Table Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

CHAPTER 4. WORKING WITH SPOOLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77


Creating a Spool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Working with a Spool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Printing the Spool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Spool Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
ii—Table of Contents

CHAPTER 5. STRINGS AND DATES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85


Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .85
Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

CHAPTER 6. EVIEWS PROGRAMMING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .129


Program Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Simple Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Program Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Program Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Program Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Program Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Control of Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .157
Multiple Program Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
User-Defined Dialogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178
Version 4 Compatibility Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

CHAPTER 7. EXTERNAL CONNECTIVITY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193


Reading EViews Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193
EViews COM Automation Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
EViews COM Automation Client Support (MATLAB, R, Python) . . . . . . . . . . . . . . . . . . . . . . .195
EViews Database Extension Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Jupyter Notebook Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .205

CHAPTER 8. ADD-INS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207


What is an Add-in? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Getting Started with Add-ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207
Using Add-ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .211
Add-ins Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Managing Add-ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Creating an Add-in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .222
Add-ins Design Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .230

CHAPTER 9. USER OBJECTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233


What is a User Object? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Unregistered User Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Registered User Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .236
Table of Contents—iii

Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Managing User Object Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Defining a Registered User Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
User Object Programming Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257

CHAPTER 10. USER-DEFINED OPTIMIZATION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261


Defining the Objective and Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
The Optimize Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
Technical Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278

CHAPTER 11. MATRIX LANGUAGE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279


Declaring Matrix Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Assigning Matrix Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Copying Data Between Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Matrix Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Matrix Commands and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Matrix Views and Procs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Matrix Operations versus Loop Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303

CHAPTER 12. WORKFILE FUNCTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305


Basic Workfile Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Workfile Sample Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Dated Workfile Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Panel Workfile Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320

CHAPTER 13. SPECIAL EXPRESSION REFERENCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323


CHAPTER 14. STRING AND DATE SUMMARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
String Function Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Date Function Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333

CHAPTER 15. MATRIX LANGUAGE SUMMARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335


Matrix Command Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Matrix Function Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

CHAPTER 16. PROGRAMMING LANGUAGE SUMMARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343


Program Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Support Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
iv—Table of Contents

Support Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345


Workfile Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Dialog Display Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

CHAPTER 17. COMMAND REFERENCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .357


CHAPTER 18. FUNCTION REFERENCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .679
Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
Function Summaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .681
Function Reference: A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713
Function Reference: B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721
Function Reference: C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
Function Reference: D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
Function Reference: E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 859
Function Reference: F . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 881
Function Reference: G . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891
Function Reference: H . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
Function Reference: I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .913
Function Reference: J . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .933
Function Reference: K . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 935
Function Reference: L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 939
Function Reference: M . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
Function Reference: N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1009
Function Reference: O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1015
Function Reference: P . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1023
Function Reference: Q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1045
Function Reference: R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1061
Function Reference: S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1107
Function Reference: T . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1143
Function Reference: U . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1159
Function Reference: V . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1175
Function Reference: W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1187
Function Reference: X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1219
Function Reference: Y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1223
Function Reference: Z . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1225

APPENDIX A. WILDCARDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1227


Wildcard Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1227
Table of Contents—v

Using Wildcard Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1227


Source and Destination Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1228
Resolving Ambiguities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1229
Wildcard versus Pool Identifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1230

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1233
vi—Table of Contents
Preface

The EViews User’s Guide focuses primarily on interactive use of EViews using dialogs and
other parts of the graphical user interface.

Alternatively, you may use EViews’ powerful command and batch processing language to
perform almost every operation that can be accomplished using the menus. You can enter
and edit commands in the command window, or you can create and store the commands in
programs that document your research project for later execution.

This text, the EViews Command and Programming Reference, documents the use of com-
mands in EViews, along with examples of commands for commonly performed operations,
and provides general information about the command, programming, and matrix languages:

The first chapter provides an overview of using commands in EViews:


• Chapter 1. “Object and Command Basics,” on page 3 explains the basics of using
commands to work with EViews objects, and provides examples of some commonly
performed operations.

The next set of chapters discusses commands for working with specific EViews objects:
• Chapter 2. “Working with Graphs,” on page 33 describes the use of commands to cus-
tomize graph objects.
• Chapter 3. “Working with Tables and Spreadsheets,” on page 57 documents the table
object and describes the basics of working with tables in EViews.
• Chapter 4. “Working with Spools,” on page 77 discusses commands for working with
spools.

The EViews programming and matrix language are described in:


• Chapter 5. “Strings and Dates,” on page 85 describes the syntax and functions avail-
able for manipulating text strings and dates.
• Chapter 6. “EViews Programming,” on page 129 describes the basics of using pro-
grams for batch processing and documents the programming language.
• Chapter 11. “Matrix Language,” on page 279 describes the EViews matrix language.
• Chapter 7. “External Connectivity,” on page 193 documents EViews features for inter-
facing with external applications through the OLEDB driver and various COM automa-
tion interfaces.

The remaining chapters contain reference material:


2—Preface

• Chapter 17. “Command Reference,” on page 357 is the primary reference for com-
mands to work with EViews objects, workfiles, databases, external interfaces, pro-
grams, as well as other auxiliary commands.
• Chapter 18. “Function Reference,” on page 679 offers an alphabetical list of element
operators, numerical functions and descriptive statistics functions.

There is additional material in the appendix:


• Appendix A. “Wildcards,” on page 1227 describes the use of wildcards in different
contexts in EViews.
Chapter 1. Object and Command Basics

This chapter provides an brief overview of the command method of working with EViews
and EViews objects. The command line interface of EViews is comprised of a set of single
line commands, each of which may be classified as one of the following:
• object declarations and assignment statements.
• object view and procedure commands.
• interactive commands for creating objects and displaying views and procedures.
• auxiliary commands.

The following sections provide an overview of each of the command types. But before dis-
cussing the various types, we offer a brief discussion of the interactive and batch methods of
using commands in EViews.

Command Capture
Before beginning our in-depth discussion of commands in EViews, we note that a great way
to familiarize yourself with the EViews command language is to use command capture. With
command capture, when you perform an operation using the user-interface, EViews will
save the equivalent text command for display and export.

EViews offers command capture for most object views and procedures, and a large number
of interactive operations.

To enable command capture you must display the command capture window. To display the
window or set focus on the window, click on Window/Display Command Capture Win-
dow from the main EViews menu.
4—Chapter 1.Command Capture

Once opened, you may move and resize the capture window as desired. The window may
even be pinned or moved outside of the frame of the EViews application (see “Command
and Capture Window Docking” on page 10).

Additionally, you may choose to echo any captured commands to the command window. To
enable this feature, select Options/General Options from the manu menu, and click on the
Command Capture node, and click on the Capture to Command Window checkbox.

You can copy-and-paste the contents of the capture window, or you can save the contents to
a file. Right-clicking in the window brings up a menu for copying or clearing the window,
saving the contents to a file on disk, or opening a new, untitled program containing the con-
tents of the window.

Note that not all interactive operations in EViews are capture enabled. Among the notable
exceptions are some types of graph creation and customization, and individual cell editing
for tables and spreadsheets. In addition, capture of object view graph customization is not
supported. Thus, if you wish to capture the commands for customizing the impulse
response view of a VAR object, you should freeze the view, and then customize the frozen
graph object.
Using Commands—5

Using Commands
Commands may be used interactively or executed in batch mode.

Interactive Use
The command window is located (by default) just below the main menu bar at the top of the
EViews window. A blinking insertion cursor in the command window indicates that key-
board focus is in the command window and that keystrokes will be entered in the window at
the insertion point. If no insertion cursor is present, simply click in the command window to
change the focus.

To work interactively, you will type a command into the command window, then press
ENTER to execute the command. If you enter an incomplete command, EViews will open a
dialog box prompting you for additional information.

A command that you


enter in the window will
be executed as soon as
you press ENTER. The
insertion point need not
be at the end of the com-
mand line when you
press ENTER. EViews
will execute the entire line that contains the insertion point.

The contents of the command area may also be saved directly into a text file for later use.
First make certain that the command window is active by clicking anywhere in the window,
and then select File/Save As… from the main menu. EViews will prompt you to save an
ASCII file in the default working directory (default name “commandlog.txt”) containing the
entire contents of the command window.

Command Window Editing


When you enter a command, EViews will add it to the list of previously executed commands
contained in the window. You can scroll up to an earlier command, edit it, and hit ENTER.
The modified command will be executed. You may also use standard Windows copy-and-
paste between the command window and any other window.

EViews offers a couple of specialized tools for displaying previous commands. First, to bring
up previous commands in the order they were entered, press the Control key and the UP
arrow (CTRL+UP). The last command will be entered into the command window. Holding
down the CTRL key and pressing UP repeatedly will display the next prior commands.
Repeat until the desired command is displayed.
6—Chapter 1.Using Commands

To look at a history of commands, press the Control Key and the J key (CTRL+J). This key
combination displays a history window containing the last 30 commands executed. Use the
UP and DOWN arrows until the desired command is selected and then press the ENTER key
to add it to the command window, or simply double click on the desired command. To close
the history window without selecting a command, click elsewhere in the command window
or press the Escape (ESC) key.

To execute the retrieved command, simply press ENTER again. You may first edit the com-
mand if you wish to do so.

You may resize the command window so that a larger number of previously executed com-
mands are visible. Use the mouse to move the cursor to the bottom of the window, hold
down the mouse button, and drag the bottom of the window downwards.

Command Explorer
The Command Explorer provides a quick way to display context specific documentation
while working in EViews. In particular, you may use the explorer to list all of the applicable
commands and data members for a specific object type, and to display documentation for
those commands.

By default, EViews ships with the explorer window in a docked window on the right-hand
side of your EViews window. To activate the explorer, simply click on the tab labeled Com-
mand Explorer.

EViews will open a window showing a list of the EViews object types.
Using Commands—7

• Clicking on the name of an object type will open a documentation page for that object
in a browser window.
• Clicking on the arrow to the left of the object name will toggle the display of alphabet-
ical tree-listing of all of the commands, procs, and data members for that object. To
open a browser window to the documentation of a given element, click on the name.

Alternately, from the open explorer window, you may use the search box to locate a specific
command or proc.

if you already know the command name or a portion of the command name, you may
search for the command by simply typing portion of that command followed by a wildcard
(“*”) into the search window and pressing return. A list of matching commands will be dis-
played. Clicking on one of the results will display the corresponding help page.
8—Chapter 1.Using Commands

Use the left and right arrows to the left of the search window to switch between the search
results and the full list of commands.

By default, the Command Explorer window will automatically close when it loses focus. You
may click on the push-pin in the upper right portion of the window to dock the open win-
dow. Click on the push-pin again to restore the docked window to auto-close.

Auto-Complete Names and Commands


You may instruct EViews to auto-complete the name of the object or object command you
are in the middle of typing. This feature is particularly useful in workfiles with long series
names or when issuing a series of commands. (Note that auto-complete is only enabled
when there is a workfile open).

Object Name Auto-Complete


Assuming you have an open workfile, simply begin typing the first characters of the name of
an object or command. Press CONTROL+SPACE to display a list of the objects in the current
workfile.
Ne

If there are no ambiguities, the name of the object will be added to the command window. If
there are ambiguities, a list of all the objects in the workfile will appear with the first match
selected:
Using Commands—9

From here you can either press ENTER and the name of the object will be completed, or you
may use the up and down arrows to select a name and press ENTER to complete your selec-
tion:

Alternately, you may press CONTROL+SPACE at any time when nothing has been typed, to
see the full list of objects.

Object Command Auto-Complete


Similarly, you may use auto-completion for commands. If you have typed an object name
along with a trailing period, press CONTROL+SPACE again to display the list of commands
for that object. Assuming that object exists in your current workfile, EViews will list all the
commands and procs for that object,

As with object name auto-complete, typing a portion of a command will add the full string if
there are no ambiguities, or will display a list of applicable commands with the nearest
match partially selected:

Using the arrow keys, select the desired command:


10—Chapter 1.Using Commands

and press ENTER to add the command to the window:

Command and Capture Window Docking


The EViews 14 command and capture windows are dockable, hideable, and floatable.

Dockable and hideable windows allow you to move frequently used windows out of the way
while keeping them close at hand. They offer space saving convenience which is particu-
larly valued when working with smaller screen devices like laptops.

Floatable windows allow you to move them out of the way of your work. You may even go
so far as to float a window outside of the EViews frame.

To re-arrange the layout of the Command or Capture window, first make sure the window
pane is not in sliding mode (the Pin icon should be IN so that it is vertical).

Then drag the window to the desired location or dock.

Note that it is possible to drag a window into an unwanted position where it covers a por-
tion of a window with which you wish to work. In most cases, you may simply move the
window out of the way. If it is difficult to drag the window because you cannot see the title-
bar, you should be able use the scroll bars to gain easier access to the titlebar of the window.

Floating
You can drag the window to a new location just like any other window in EViews. However,
unlike other EViews windows, You can drag the command window outside of the EViews
frame:
Using Commands—11

Docking
Both the command and capture window panes can now be docked on any side inside the
main EViews window. Begin dragging the pane by left-clicking title bar and holding it down
as you drag it off the edge. At that point, you will see small docking guides appear inside the
main EViews window:
12—Chapter 1.Using Commands

To dock the window, you will drag it to one of the docking guides. The docking behavior
will depend on which guide you select.

The docking guides allow you to dock the window pane to one of eight pre-defined areas.
The four guides on the outer edge of the main window allow you to dock the window as the
primary pane while the inner guides allow you to dock the window as a secondary pane. Pri-
mary panes take over the entire length of the selected edge and force other docked panes
that could intersect to become smaller to compensate. Secondary panes only take over the
portion of the selected edge that is not already occupied.

For example, if the capture pane is dragged to the right-most docking guide like this:

and then released, the final layout looks like this


Using Commands—13

Because it is primary, it pushes the docked Command window pane at the top of the win-
dow to become smaller.

Alternatively, if the inner right guide was selected instead like this:
14—Chapter 1.Using Commands

the final layout would look like this

Docking two panes onto the same primary edge can result in stacking, with the recently
moved pane being adjacent to the edge (as the primary), and any secondary panes being
stacked next to the primary pane (in the order they were docked).
Using Commands—15

You can also dock a pane inside another pane in order to use the share the same space. If
you drag a pane over another pane, you are presented with additional docking guides inside
the other pane:

For example, selecting the inner-right guide area allows the Capture pane to appear to the
right of the Command pane with an adjustable split bar to let you resize the split:
16—Chapter 1.Using Commands

The docking guide also offers an additional guide area directly in the center that allows you
to convert both panes into a tabbed view:
Using Commands—17

Pinning
If your window is docked, you can “pin” it by clicking on the pin icon (so that it is horizon-
tal). When pinned, the window will be minimized and a small tab will be displayed in the
docked location.

To expand the pinned window, simply click on the tab. The window will automatically con-
tracts when it loses focus. Clicking on the Pin icon again will “un-pin” and expand the win-
dow permanently.

See also “Pane and Tab User Interface” on page 97 of User’s Guide I for an alternative user
interface that extends the use of docking and pinning.

Keyboard Focus
We note that as you open and close object windows in EViews, the keyboard focus may
change from the command window to the active window. If you then wish to enter a com-
mand, you will first need to click in the command window to set the focus. You can influ-
ence EViews’ method of choosing keyboard focus by changing the global defaults—simply
select Options/General Options.../Window Behavior in the main menu, and change the
Keyboard Focus setting as desired.

Batch Program Use


You may assemble a number of commands into a program, and then execute the commands
in batch mode. Each command in the program will be executed in the order that it appears
in the program. Using batch programs allows you to make use of advanced capabilities such
18—Chapter 1.Object Declaration and Initialization

as looping and condition branching, and subroutine and macro processing. Programs also
are an excellent way to document a research project since you will have a record of each
step of the project. Batch program use of EViews is discussed in greater detail in Chapter 6.
“EViews Programming,” on page 129.

One way to create a program file in EViews is to select File/New/Program. EViews will
open an untitled program window into which you may enter your commands. You can save
the program by clicking on the Save or SaveAs button, navigating to the desired directory,
and entering a file name. EViews will append the extension “.PRG” to the name you provide.

Alternatively, you can use your favorite text (ASCII) editor to create a program file contain-
ing your commands. It will prove convenient to name your file using the extension “.PRG”.
The commands in this program may then be executed from within EViews.

You may also enter commands in the command window and then use File/Save As... to
save the log for editing.

Object Declaration and Initialization


The simplest types of commands create an EViews object, or assign data to or initialize an
existing object.

Object Declaration
A simple object declaration has the form
object_type(options) object_name
where object_name is the name you would like to give to the newly created object and
object_type is one of the following object types:

Alpha (p. 6) Pool (p. 650) Sym (p. 991)

Coef (p. 22) Rowvector (p. 703) System (p. 1031)

Equation (p. 51) Sample (p. 738) Table (p. 1072)

Factor (p. 273) Scalar (p. 747) Text (p. 1112)

Graph (p. 368) Series (p. 755) User (p. 1122)

Group (p. 436) Spool (p. 904) Valmap (p. 1133)


Object Declaration and Initialization—19

Logl (p. 537) Sspace (p. 931) Var (p. 1141)

Matrix (p. 554) String (p. 961) Vector (p. 1221)

Model (p. 606) Svector (p. 968)

Details on each of the commands associated with each of these objects are provided in the
section beginning on the specified page in the Object Reference.

For example, the declaration,


series lgdp

creates a new series called LGDP, while the command:


equation eq1

creates a new equation object called EQ1.

Matrix objects are typically declared with their dimension as an option provided in paren-
theses after the object type. For example:
matrix(5,5) x

creates a 5  5 matrix named X, while


coef(10) results

creates a 10 element coefficient vector named RESULTS.

Simple declarations initialize the object with default values; in some cases, the defaults have
a meaningful interpretation, while in other cases, the object will simply be left in an incom-
plete state. In our examples, the newly created LGDP will contain all NA values and X and
RESULTS will be initialized to 0, while EQ1 will be simply be an uninitialized equation con-
taining no estimates.

Note that in order to declare an object you must have a workfile currently open in EViews.
You may open or create a workfile interactively from the File Menu or drag-and-dropping a
file onto EViews (see Chapter 2. “Workfile Basics,” on page 29 of User’s Guide I for details),
or you can may use the wfopen (p. 640) command to perform the same operations inside a
program.

Object Assignment
Object assignment statements are commands which assign data to an EViews object using
the “=” sign. Object assignment statements have the syntax:
object_name = expression
20—Chapter 1.Object Declaration and Initialization

where object_name identifies the object whose data is to be modified and expression is an
expression which evaluates to an object of an appropriate type. Note that not all objects per-
mit object assignment; for example, you may not perform assignment to an equation object.
(You may, however, initialize the equation using a command method.)

The nature of the assignment varies depending on what type of object is on the left hand
side of the equal sign. To take a simple example, consider the assignment statement:
x = 5 * log(y) + z

where X, Y and Z are series. This assignment statement will take the log of each element of
Y, multiply each value by 5, add the corresponding element of Z, and, finally, assign the
result into the appropriate element of X.

Similarly, if M1, M2, and M3 are matrices, we may use the assignment statement:
m1 = @inverse(m2) * m3

to postmultiply the matrix inverse of M2 by M3 and assign the result to M1. This statement
presumes that M2 and M3 are suitably conformable.

Object Modification
In cases where direct assignment using the “=” operator is not allowed, one may initialize
the object using one or more object commands. We will discuss object commands in greater
detail in a moment (see “Object Commands,” on page 21) but for now simply note that
object commands may be used to modify the contents of an existing object.

For example:
eq1.ls log(cons) c x1 x2

uses an object command to estimate the linear regression of the LOG(CONS) on a constant,
X1, and X2, and places the results in the equation object EQ1.
sys1.append y=c(1)+c(2)*x
sys1.append z=c(3)+c(4)*x
sys1.ls

adds two lines to the system specification, then estimates the specification using system
least squares.

Similarly:
group01.add gdp cons inv g x

adds the series GDP, CONS, INV, G, and X to the group object GROUP01.
Object Commands—21

More on Object Declaration


Object declaration may often be combined with assignment or command initialization. For
example:
series lgdp = log(gdp)

creates a new series called LGDP and initializes its elements with the log of the series GDP.
Similarly:
equation eq1.ls y c x1 x2

creates a new equation object called EQ1 and initializes it with the results from regressing
the series Y against a constant term, the series X1 and the series X2.

Lastly:
group group01 gdp cons inv g x

create the group GROUP01 containing the series GDP, CONS, INV, G, and X.

An object may be declared multiple times so long as it is always declared to be of the same
type. The first declaration will create the object, subsequent declarations will have no effect
unless the subsequent declaration also specifies how the object is to be initialized. For
example:
smpl @first 1979
series dummy = 1
smpl 1980 @last
series dummy=0

creates a series named DUMMY that has the value 1 prior to 1980 and the value 0 thereafter.

Redeclaration of an object to a different type is not allowed and will generate an error.

Object Commands
Most of the commands that you will employ are object commands. An object command is a
command which displays a view of or performs a procedure using a specific object. Object
commands have two main parts: an action followed by a view or procedure specification.
The (optional) display action determines what is to be done with the output from the view
or procedure. The view or procedure specification may provide for options and arguments to
modify the default behavior.

The complete syntax for an object command has the form:


action(action_opt) object_name.view_or_proc(options_list) arg_list
where:
action....................is one of the four verb commands (do, freeze, print, show).
22—Chapter 1.Object Commands

action_opt ............ an option that modifies the default behavior of the action.
object_name.......... the name of the object to be acted upon.
view_or_proc ........ the object view or procedure to be performed.
options_list .......... an option that modifies the default behavior of the view or proce-
dure.
arg_list ................ a list of view or procedure arguments.

Action Commands
There are four possible action commands:
• show displays the object view in a window.
• do executes procedures without opening a window. If the object’s window is not cur-
rently displayed, no output is generated. If the objects window is already open, do is
equivalent to show.
• freeze creates a table or graph from the object view window.
• print prints the object view window.

As noted above, in most cases, you need not specify an action explicitly. If no action is spec-
ified, the show action is assumed for views and the do action is assumed for most proce-
dures (though some procedures will display newly created output in new windows unless
the command was executed via a batch program).

For example, when using an object command to display the line graph series view, EViews
implicitly adds a show command. Thus, the following two lines are equivalent:
gdp.line
show gdp.line

In this example, the view_or_proc argument is line, indicating that we wish to view a line
graph of the GDP data. There are no additional options or arguments specified in the com-
mand.

Alternatively, for the equation method (procedure) ls, there is an implicit do action:
eq1.ls cons c gdp
do eq1.ls cons c gdp

so that the two command lines describe equivalent behavior. In this case, the object com-
mand will not open the window for EQ1 to display the result. You may display the window
by issuing an explicit show command after issuing the initial command:
show eq1

or by combining the two commands:


show eq1.ls cons c gdp
Object Commands—23

Similarly:
print eq1.ls cons c gdp

both performs the implicit do action and then sends the output to the printer.

The following lines show a variety of object commands with modifiers:


show gdp.line
print(l) group1.stats
freeze(output1) eq1.ls cons c gdp
do eq1.forecast eq1f

The first example opens a window displaying a line graph of the series GDP. The second
example prints (in landscape mode) descriptive statistics for the series in GROUP1. The third
example creates a table named OUTPUT1 from the estimation results of EQ1 for a least
squares regression of CONS on GDP. The final example executes the forecast procedure of
EQ1, putting the forecasted values into the series EQ1F and suppressing any procedure out-
put.

Of these four examples, only the first opens a window and displays output on the screen.

Output Control
As noted above, the display action determines the destination for view and procedure out-
put. Here we note in passing a few extensions to these general rules.

You may request that a view be simultaneously printed and displayed on your screen by
including the letter “p” as an option to the object command. For example, the expression,
gdp.correl(24, p)

is equivalent to the two commands:


show gdp.correl(24)
print gdp.correl(24)

since correl is a series view. The “p” option can be combined with other options, sepa-
rated by commas. So as not to interfere with other option processing, we recommend that
the “p” option always be specified after any required options.

Note that the print command accepts the “l” or “p” option to indicate landscape or portrait
orientation. For example:
print(l) gdp.correl(24)

Printer output can be redirected to a text file, frozen output, or a spool object. (See output
(p. 533), and the discussion in “Print Setup” on page 2562 of User’s Guide I for details.)

The freeze command used without options creates an untitled graph or table from a view
specification:
24—Chapter 1.Object Commands

freeze gdp.line

You also may provide a name for the frozen object in parentheses after the word freeze.
For example:
freeze(figure1) gdp.bar

names the frozen bar graph of GDP as “figure1”.

View and Procedure Commands


Not surprisingly, the view or procedure commands correspond to elements of the views and
procedures menus for the various objects.

For example, the top level of the view menu for the series
object allows you to: display a spreadsheet view of the data,
graph the data, perform a one-way tabulation, compute and
display a correlogram or long-run variance, perform unit root
or variance ratio tests, conduct a BDS independence test, or
display or modify the label view.

Object commands exist for each of these views. Suppose for


example, that you have the series object SER01. Then:
ser01.sheet
ser01.stats

display the spreadsheet and descriptive statistics views of the data in the series. There are a
number of graph commands corresponding to the menu entry, so that you may enter:
ser01.line
ser01.bar
ser01.hist

which display a line graph, bar graph, and histogram, respectively, of the data in SER01.
Similarly,
ser01.freq

performs a one-way tabulation of the data, and:


ser01.correl
ser01.lrvar
ser01.uroot
ser01.vratio 2 4 8
ser01.bdstest

display the correlogram and long-run variances, and conduct unit root, variance ratio, and
independence testing for the data in the series. Lastly:
Object Data Members—25

ser01.label(r) "this is the added series label"

appends the text “this is the added series label” to the end of the remarks field.

There are commands for all of the views and procedures of each EViews object. Details on
the syntax of each of the object commands may be found in Chapter 1. “Object View and
Procedure Reference,” beginning on page 3 in the Object Reference.

Object Data Members


Every object type in EViews has a selection of global data members. Custom data members
object may also be added to an object. These members contain information about the object
and can be retrieved from an object to be used as part of another command, or stored into
the workfile as a new object.

Custom attributes must be added interactively via the label view of an object. Retrieving
custom and default data members however can be accessed by using the “@attr” data mem-
ber.

The following data members belong to every object type in EViews:

Data Member Name Description


Returns the name of the
@name
object
Returns the display name of
the object. If the object has
@displayname
no display name, the name is
returned
@type Returns the object type
Returns the description of the
@description
object (if available)
Returns the remarks of the
@remarks
object (if available)
Returns the string representa-
@updatetime tion of the time the object
was last updated

Along with these global data members, each object type has a set of data members specific
to that type. For example, equation objects have a data member, @r2, that returns a scalar
containing the R-squared from that equation. Groups have an member, @count, that returns
a scalar containing the number of series contained within that group. A full list of each
object’s data members can be found under the object’s section in Chapter 1. “Object View
and Procedure Reference,” on page 3 of the Object Reference.
26—Chapter 1.Interactive Commands

As an example of using data members, the commands:


equation eq1.ls y c x1 x2
table tab1
tab1(1,1) = eq1.@f

create an equation named EQ1 and a table named TAB1, and then set the first cell of the
table equal to the F-statistic from the estimated equation.

Interactive Commands
There is also a set of auxiliary commands which are designed to facilitate interactive use.
These commands perform the same operations as equivalent object commands, but do so
on newly created, unnamed objects. For example, the command:
ls y c x1 x2

will regress the series Y against a constant term, the series X1 and the series X2, and create
a new untitled equation object to hold the results.

Similarly, the command:


scat x y

creates an untitled group object containing the series X and Y and then displays a scatterplot
of the data in the two series.

Since these commands are designed primarily for interactive use, they are designed for car-
rying out simple tasks. Overuse of these interactive tools, or their use in programs, will
make it difficult to manage your work since unnamed objects cannot be referenced by name
from within a program, cannot be saved to disk, and cannot be deleted except through the
graphical Windows interface. In general, we recommend that you use named objects rather
than untitled objects for your work. For example, we may replace the first auxiliary com-
mand above with the statement:
equation eq1.ls y c x1 x2

to create the named equation object EQ1. This example uses declaration of the object EQ1
and the equation method ls to perform the same task as the auxiliary command above.

Similarly,
group mygroup x y
mygroup.scat

displays the scatterplot of the series in the named group MYGROUP.


Auxiliary Commands—27

Auxiliary Commands
Auxiliary commands are commands which are unrelated to a particular object (i.e., are not
object views or procs), or act on an object in a way that is generally independent of the type
or contents of the object. Many of the important auxiliary commands are used for managing
objects, and object containers. A few of the more important commands are described below.

Auxiliary commands typically follow the syntax:


command(option_list) argument_list
where command is the name of the command, option_list is a list of options separated by
commas, and argument_list is a list of arguments generally separated by spaces.

An example of an auxiliary command is:


store(d=c:\newdata\db1) gdp m x

which will store the three objects GDP, M and X in the database named DB1 in the directory
C:\NEWDATA.

Managing Workfiles and Databases


There are two types of object containers: workfiles and databases. All EViews objects must
be held in an object container, so before you begin working with objects you must create a
workfile or database. Workfiles and databases are described in depth in Chapter 2. “Workfile
Basics,” beginning on page 29 and Chapter 10. “EViews Databases,” beginning on page 333
of User’s Guide I.

Managing Workfiles
To declare and create a new workfile, you may use the wfcreate (p. 634) command. You
may enter the keyword wfcreate followed by a name for the workfile, an option for the fre-
quency of the workfile, and the start and end dates. The most commonly used workfile fre-
quency type options are:

a annual.
s semi-annual.
q quarterly.
m monthly.
w weekly.
d daily (5 day week).
7 daily (7 day week).
u undated/unstructured.
28—Chapter 1.Auxiliary Commands

but there are additional options for multi-year, bimonthly, fortnight, ten-day, daily with cus-
tom week, intraday, integer date, and undated frequency workfiles.

For example:
wfcreate macro1 q 1965Q1 1995Q4

creates a new quarterly workfile named MACRO1 from the first quarter of 1965 to the fourth
quarter of 1995.
wfcreate cps88 u 1 1000

creates a new undated workfile named CPS88 with 1000 observations.

Alternately, you may use wfopen (p. 640) to read a foreign data source into a new workfile.

If you have multiple open workfiles, the wfselect (p. 663) command may be used to
change the active workfile.

To save the active workfile, use the wfsave (p. 656) command by typing the keyword
wfsave followed by a workfile name. If any part of the path or workfile name has spaces,
you should enclose the entire expression in quotation marks. The active workfile will be
saved in the default path under the given name. You may optionally provide a path to save
the workfile in a different directory:
wfsave a:\mywork

If necessary, enclose the path name in quotations.

To close the workfile, use the close (p. 393) command. For example:
close mywork

closes the workfile window of MYWORK.

To open a previously saved workfile, use the wfopen (p. 640) command. You should follow
the keyword with the name of the workfile. You can optionally include a path designation to
open workfiles that are not saved in the default path. For example:
wfopen "c:\mywork\proj1"

Managing Databases
To create a new database, follow the dbcreate (p. 426) command keyword with a name for
the new database. Alternatively, you could use the db (p. 424) command keyword followed
by a name for the new database. The two commands differ only when the named database
already exists.

If you use dbcreate and the named database already exists on disk, EViews will error indi-
cating that the database already exits. If you use db and the named database already exists
Auxiliary Commands—29

on disk, EViews will simply open the existing database. Note that the newly opened data-
base will become the default database.

For example:
dbcreate mydata1

creates a new database named MYDATA1 in the default path, opens a new database win-
dow, and makes MYDATA1 the default database.
db c:\evdata\usdb

opens the USDB database in the specified directory if it already exists. If it does not, EViews
creates a new database named USDB, opens its window, and makes it the default database.

You may use dbopen (p. 428) to open an existing database and to make it the default data-
base. For example:
dbopen findat

opens the database named FINDAT in the default directory. If the database does not exist,
EViews will error indicating that the specified database cannot be found.

You may use dbrename to rename an existing database. Follow the dbrename keyword by
the current (old) name and a new name:
dbrename temp1 newmacro

To delete an existing database, use the dbdelete (p. 428) command. Follow the dbdelete
keyword by the name of the database to delete:
dbdelete c:\data\usmacro

dbcopy (p. 424) makes a copy of the existing database. Follow the dbcopy keyword with
the name of the source file and the name of the destination file:
dbcopy c:\evdata\macro1 a:\macro1

dbpack (p. 431) and dbrebuild (p. 431) are database maintenance commands. See also
Chapter 10. “EViews Databases,” beginning on page 333 of User’s Guide I for a detailed
description.

Managing Objects
In the course of a program you will often need to manage the objects in a workfile by copy-
ing, renaming, deleting and storing them to disk. EViews provides a number of auxiliary
commands which perform these operations. The following discussion introduces you to the
most commonly used commands; a full description of these, and other commands is pro-
vided in Chapter 17. “Command Reference,” on page 357.
30—Chapter 1.Auxiliary Commands

Copying Objects
You may create a duplicate copy of one or more objects using the copy (p. 411) command.
The copy command is an auxiliary command with the format:
copy source_name dest_name

where source_name is the name of the object you wish to duplicate, and dest_name is the
name you want attached to the new copy of the object.

The copy command may also be used to copy objects in databases and to move objects
between workfiles and databases.

Copy with Wildcard Characters


EViews supports the use of wildcard characters (“?” for a single character match and “*” for
a pattern match) in destination specifications when using the copy and rename commands.
Using this feature, you can copy or rename a set of objects whose names share a common
pattern in a single operation. This features is useful for managing series produced by model
simulations, series corresponding to pool cross-sections, and any other situation where you
have a set of objects which share a common naming convention.

A destination wildcard pattern can be used only when a wildcard pattern has been provided
for the source, and the destination pattern must always conform to the source pattern in that
the number and order of wildcard characters must be exactly the same between the two. For
example, the patterns:

Source Pattern Destination Pattern


x* y*
*c b*
x*12? yz*f?abc

conform to each other. These patterns do not:

Source Pattern Destination Pattern


a* b
*x ?y
x*y* *x*y*

When using wildcards, the destination name is formed by replacing each wildcard in the
destination pattern by the characters from the source name that matched the corresponding
wildcard in the source pattern. Some examples should make this principle clear:
Auxiliary Commands—31

Source Pattern Destination Pattern Source Name Destination Name


*_base *_jan x_base x_jan
us_* * us_gdp gdp
x? x?f x1 x1f
*_* **f us_gdp usgdpf
??*f ??_* usgdpf us_gdp

Note, as shown in the second example, that a simple asterisk for the destination pattern
does not mean to use the unaltered source name as the destination name. To copy objects
between containers preserving the existing name, either repeat the source pattern as the des-
tination pattern,
copy x* db1::x*

or omit the destination pattern entirely:


copy x* db1::

If you use wildcard characters in the source name and give a destination name without a
wildcard character, EViews will keep overwriting all objects which match the source pattern
to the name given as destination.

For additional discussion of wildcards, see Appendix A. “Wildcards,” on page 1227.

Renaming Objects
You can give an object a different name using the rename (p. 573) command. The rename
command has the format:
rename source_name dest_name

where source_name is the original name of the object and dest_name is the new name you
would like to give to the object.

rename can also be used to rename objects in databases.

You may use wildcards when renaming series. The name substitution rules are identical to
those described above for copy.

Deleting Objects
Objects may be removed from the workfile or a database using the delete command. The
delete command has the format:
delete name_pattern

where name_pattern can either be a simple name such as “XYZ”, or a pattern containing
the wildcard characters “?” and “*”, where “?” means to match any one character, and “*”
32—Chapter 1.Auxiliary Commands

means to match zero or more characters. When a pattern is provided, all objects in the
workfile with names matching the pattern will be deleted. Appendix A. “Wildcards,” on
page 1227 describes further the use of wildcards.

Saving Objects
All named objects will be saved automatically in the workfile when the workfile is saved to
disk. You can store and retrieve the current workfile to and from disk using the wfsave
(p. 656) and wfopen (p. 640) commands. Unnamed objects will not be saved as part of the
workfile.

You can also save objects for later use by storing them in a database. The store (p. 600)
command has the format:
store(option_list) object1 object2 …

where object1, object2, ..., are the names of the objects you would like to store in the data-
base. If no options are provided, the series will be stored in the current default database (see
Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of the
default database). You can store objects into a particular database by using the option
“d=db_name” or by prepending the object name with a database name followed by a dou-
ble colon “::”, such as:
store db1::x db2::x

Fetch Objects
You can retrieve objects from a database using the fetch (p. 449) command. The fetch
command has the same format as the store command:
fetch(option_list) object1 object2 …

To specify a particular database use the “d=” option or the “::” extension as for store.
Chapter 2. Working with Graphs

EViews provides an extensive set of commands to generate and customize graphs from the
command line or using programs. A summary of the graph commands described below may
be found under “Graph” on page 368 of the Object Reference.

In addition, Chapter 15. “Graph Objects,” on page 867 of User’s Guide I describes graph cus-
tomization in detail, focusing on the interactive method of working with graphs.

Creating a Graph
There are three types of graphs in EViews: graphs that are views of other objects, and named
or unnamed graph objects. The commands provided for customizing the appearance of your
graphs are available for use with named graph objects. You may use the dialogs interactively
to modify the appearance of all types of graphs.

Displaying graphs using commands


The simplest way to display a graph view is to use one of the basic graph commands.
(“Graph Creation Commands” on page 361 provides a convenient listing.)

Where possible EViews will simply open the object and display the appropriate graph view.
For example, to display a line or bar graph of the series INCOME and CONS, you may simply
issue the commands:
line income
bar cons

In other cases, EViews must first create an unnamed object and then will display the desired
view of that object. For example:
scat x y z

first creates an unnamed group object containing the three series and then, using the scat
view of a group, displays scatterplots of Y on X and Z on X in a single frame.

As with other EViews commands, graph creation commands allow you to specify a variety
of options and arguments to modify the default graph settings. You may, for example, rotate
the bar graph using the “rotate” option,
bar(rotate) cons

or you may display boxplots along the borders of your scatter plot using:
scat(ab=boxplot) x y z
34—Chapter 2.Creating a Graph

Note that while using graph commands interactively may be quite convenient, these com-
mands are not recommended for program use since you will not be able to use the resulting
unnamed objects in your program.

The next section describes a more flexible approach to displaying graphs.

Displaying graphs as object views


You may display a graph of an existing object using a graph view command. For example,
you may use the following two commands to display graph views of a series and a group:
ser2.area(n)
grp6.xypair

The first command plots the series SER2 as an area graph with normalized scaling. The sec-
ond command provides an XY line graph view of the group GRP6, with the series plotted in
pairs.

To display graphs for multiple series, we may first create a group containing the series and
then display the appropriate view:
group g1 x y z
g1.scat

shows the scatterplot of the series in the newly created group G1.

There are a wide range of sophisticated graph views that you may display using commands.
See Chapter . “,” beginning on page 1266 of the Object Reference for a detailed listing along
with numerous examples.

Before proceeding, it is important to note that graph views of objects differ from graph
objects in important ways:
• First, graph views of objects may not be customized using commands after they are
first created. The graph commands for customizing an existing graph are designed for
use with graph objects.
• Second, while you may use interactive dialogs to customize an existing object’s graph
view, we caution you that there is no guarantee that the customization will be perma-
nent. In many cases, the customized settings will not be saved with the object and
will be discarded when the view changes or if the object is closed and then reopened.
In contrast, graph objects may be customized extensively after they are created. Any
customization of a graph object is permanent, and will be saved with the object.

Since construction of a graph view is described in detail elsewhere (Chapter . “,” beginning
on page 1266 of the Object Reference), we focus the remainder of our attention on the cre-
ation and customization of graph objects.
Creating a Graph—35

Creating graph objects from object views


If you wish to create a graph object from another object, you should combine the object
view command with the freeze command. Simply follow the freeze keyword with an
optional name for the graph object, and the object view to be frozen. For example,
freeze grp6.xypair(m)

creates and displays an unnamed graph object of the GRP6 view showing an XY line graph
with the series plotted in pairs in multiple graph frames. Be sure to specify any desired
graph options (e.g., “m”). Note that freezing an object view will not necessarily copy the
existing custom appearance settings such as line color, axis assignment, etc. For this reason
that we recommend that you create a graph object before performing extensive customiza-
tion of a view.

You should avoid creating unnamed graphs when using commands in programs since you
will be unable to refer to, or work with the resulting object in a program. Instead, you
should tell EViews to create a named object, as in:
freeze(graph1) grp6.line

which creates a graph object GRAPH1 containing a line graph of the data in GRP6. By
default, the frozen graph will have updating turned off, but in most cases you may use the
Graph::setupdate graph proc to turn updating on.

Note that using the freeze command with a name for the graph will create the graph object
and store it in the workfile without showing it. Furthermore, since we have frozen a graph
type (line) that is different from our current XY line view, existing custom appearance set-
tings will not be copied to the new graph.

Once you have created a named graph object, you may use the various graph object procs to
further customize the appearance of your graph. See “Customizing a Graph,” beginning on
page 38.

Creating named graph objects


There are three direct methods for creating a named graph object. First, you may use the
freeze command as described above. Alternatively, you may declare a graph object using
the graph command. The graph command may be used to create graph objects with a spe-
cific graph type or to merge existing graph objects.

Specifying a graph by type


To specify a graph by type you should use the graph keyword, followed by a name for the
graph, the type of graph you wish to create, and a list of series (see “Graph Type Com-
mands” on page 368 of the Object Reference for a list of types). If a type is not specified, a
line graph will be created.
36—Chapter 2.Creating a Graph

For example, both:


graph gr1 ser1 ser2
graph gr2.line ser1 ser2

create graph objects containing the line graph view of SER1 and SER2, respectively.

Similarly:
graph gr3.xyline group3

creates a graph object GR3 containing the XY line graph view of the series in GROUP3.

Each graph type provides additional options, which may be included when declaring the
graph. Among the most important options are those for controlling scaling or graph type.

The scaling options include:


• Automatic scaling (“a”), in which series are graphed using the default single scale.
The default is left scale for most graphs, or left and bottom for XY graphs.
• Dual scaling without crossing (“d”) scales the first series on the left and all other
series on the right. The left and right scales will not overlap.
• Dual scaling with possible crossing (“x”) is the same as the “d” option, but will allow
the left and right scales to overlap.
• Normalized scaling (“n”), scales using zero mean and unit standard deviation.

For example, the commands:


graph g1.xyline(d) unemp gdp inv
show g1

create and display an XY line graph of the specified series with dual scales and no crossing.

The graph type options include:


• Mixed graph (“l”) creates a single graph in which the first series is the selected graph
type (bar, area, or spike) and all remaining series are line graphs.
• Multiple graph (“m”) plots each graph in a separate frame.
• Stacked graph (“s”) plots the cumulative addition of the series, so the value of a series
is represented as the difference between the lines, bars, or areas.

For example, the commands:


group grp1 sales1 sales2
graph grsales.bar(s) grp1
show grsales
Changing Graph Types—37

create a group GRP1 containing the series SALES1 and SALES2, then create and display a
stacked bar graph GRSALES of the series in the group.

You should consult the command reference entry for each graph type for additional informa-
tion, including a list of the available options (i.e., see bar for complete details on bar
graphs, and line for details on line graphs).

Merging graph objects


The graph command may also be used to merge existing named graph objects into a named
multiple graph object. For example:
graph gr2.merge gr1 grsales

creates a multiple graph object GR2, combining two graph objects previously created.

Creating unnamed graph objects


There are two ways of creating an unnamed graph object. First, you may use the freeze
command as described in “Creating graph objects from object views” on page 35.

As we have seen earlier you may also use any of the graph type keywords as a command
(“Displaying graphs using commands” on page 33). Follow the keyword with any available
options for that type, and a list of the objects to graph. EViews will create an unnamed
graph of the specified type that is not stored in the workfile. For instance:
line(x) ser1 ser2 ser3

creates a line graph with series SER1 scaled on the left axis and series SER2 and SER3 scaled
on the right axis.

If you later decide to name this graph, you may do so interactively by clicking on the Name
button in the graph button bar. Alternatively, EViews will prompt you to name or delete any
unnamed objects before closing the workfile.

Note that there is no way to name an unnamed graph object in a program. We recommend
that you avoid creating unnamed graphs in programs since you will be unable to use the
resulting object.

Changing Graph Types


You may change the graph type of a named graph object by following the object name with
the desired graph type keyword and any options for that type. For example:
grsales.bar(l)

converts the bar graph GRSALES, created above, into a mixed bar-line graph, where SALES1
is plotted as a bar graph and SALES2 is plotted as a line graph within a single graph.
38—Chapter 2.Customizing a Graph

Note that specialized graphs, such as boxplots, place limitations on your ability to change
the graph type. In general, your ability to customize the graph settings is more limited when
changing graph types than when generating the graph from the original data.

Graph options are generally preserved when changing graph types. This includes attributes
such as line color and axis assignment, as well as objects added to the graph, such as text
labels, lines and shading. Commands to modify the appearance of named graph objects are
described in “Customizing a Graph” on page 38.

Note, however, that the line and fill graph settings are set independently. Line attributes
apply to line and spike graphs, while fill attributes apply to bar, area, and pie graphs. For
example, if you have modified the color of a line in a spike graph, this color will not be used
for the fill area if the graph is changed to an area graph.

Customizing a Graph
EViews provides a wide range of tools for customizing the appearance of a named graph
object. Nearly every display characteristic of the graph may be modified, including the
appearance of lines and filled areas, legend characteristics and placement, frame size and
attributes, and axis settings. In addition, you may add text labels, lines, and shading to the
graph.

You may modify the appearance of a graph using dialogs or via the set of commands
described below. Note that the commands are only available for graph objects since they
take the form of graph procedures.

An overview of the relationship between the tabs of the graph dialog and the associated
graph commands is illustrated below:
Customizing a Graph—39

Line characteristics
For each data line in a graph, you may modify color, width, pattern and symbol using the
Graph::setelem command. Follow the command keyword with an integer representing
the data element in the graph you would like to modify, and one or more keywords for the
characteristic you wish to change. List of symbol and pattern keywords, color keywords, and
RGB settings are provided in Graph::setelem.

To modify line color and width you should use the lcolor and lwidth keywords:
graph gr1.line ser1 ser2 ser3
gr1.setelem(3) lcolor(orange) lwidth(2)
gr1.setelem(3) lcolor(255, 128, 0) lwidth(2)

The first command creates a line graph GR1 with colors and widths taken from the global
defaults, while the latter two commands equivalently change the graph element for the third
series to an orange line 2 points wide.

Each data line in a graph may be drawn with a line, symbols, or both line and symbols. The
drawing default is given by the global options, but you may elect to add lines or symbols
using the lpattern or symbol keywords.

To add circular symbols to the line for element 3, you may enter:
gr1.setelem(3) symbol(circle)

Note that this operation modifies the existing options for the symbols, but that the line type,
color and width settings from the original graph will remain. To return to line only or sym-
bol only in a graph in which both lines and symbols are displayed, you may turn off either
symbols or patterns, respectively, by using the “none” type:
gr1.setelem(3) lpat(none)

or
gr1.setelem(3) symbol(none)

The first example removes the line from the drawing for the third series, so only the circular
symbol is used. The second example removes the symbol, so only the line is used.

If you attempt to remove the lines or symbols from a graph element that contains only lines
or symbols, respectively, the graph will change to show the opposite type. For example:
gr1.setelem(3) lpat(dash2) symbol(circle)
gr1.setelem(3) symbol(none)
gr1.setelem(3) lpat(none)

initially represents element 3 with both lines and symbols, then turns off symbols for ele-
ment 3 so that it is displayed as lines only, and finally shows element 3 as symbols only,
since the final command turns off lines in a line-only graph.
40—Chapter 2.Customizing a Graph

The examples above describe customization of the basic elements common to most graph
types. “Modifying Boxplots” on page 52 provides additional discussion of Graph::setelem
options for customizing boxplot data elements.

Use of color with lines and filled areas


By default, EViews automatically formats graphs to accommodate output in either color or
black and white. When a graph is sent to a printer or saved to a file in black and white,
EViews translates the colored lines and fills seen on the screen into an appropriate black and
white representation. The black and white lines are drawn with line patterns, and fills are
drawn with gray shading. Thus, the appearance of lines and fills on the screen may differ
from what is printed in black and white (this color translation does not apply to boxplots).

You may override this auto choice display method by changing the global defaults for
graphs. You may choose, for example, to display all lines and fills as patterns and gray
shades, respectively, whether the graph uses color or not. All subsequently created graphs
will use the new settings.

Alternatively, if you would like to override the color, line pattern, and fill settings for a given
graph object, you may use the Graph::options graph proc.

Color
To change the color setting for an existing graph object, you should use options with the
color keyword. If you wish to turn off color altogether for all lines and filled areas, you
should precede the keyword with a negative sign, as in:
gr1.options -color

To turn on color, you may use the same command with the “-” omitted.

Lines and patterns


To always display solid lines in your graph, irrespective of the color setting, you should use
options with the linesolid keyword. For example:
gr1.options linesolid

sets graph GR1 to use solid lines when rendering on the screen in color and when printing,
even if the graph is printed in black and white. Note that this setting may make identifica-
tion of individual lines difficult in a printed black and white graph, unless you change the
widths or symbols associated with individual lines (see “Line characteristics” on page 39).

Conversely, you may use the linepat option to use patterned lines regardless of the color
setting:
gr1.options linepat
Customizing a Graph—41

One advantage of using the linepat option is that it allows you to see the pattern types that
will be used in black and white printing without turning off color in your graph. For exam-
ple, using the Graph::setelem command again, change the line pattern of the second
series in GR1 to a dashed line:
gr1.setelem(2) lpat(dash1)

This command will not change the appearance of the colored lines on the screen if color is
turned on and auto choice of line and fill type is set. Thus, the line will remain solid, and
the pattern will not be visible until the graph is printed in black and white. To view the cor-
responding patterns, either turn off color so all lines are drawn as black patterned lines, or
use the linepat setting to force patterns.

To reset the graph or to override modified global settings so that the graph uses auto choice,
you may use the lineauto keyword:
gr1.options lineauto

This setting instructs the graph to use solid lines when drawing in color, and use line pat-
terns and gray shades when drawing in black and white.

Note that regardless of the color or line pattern settings, you may always view the selected
line patterns in the Lines & Symbols section of the graph options dialog. The dialog can be
brought up interactively by double clicking anywhere in the graph.

Filled area characteristics


You can modify the color, gray shade, and hatch pattern of each filled area in a bar, area, or
pie graph.

To modify these settings, use Graph::setelem, followed by an integer representing the


data element in the graph you would like to modify, and a keyword for the characteristic you
wish to change. For example, consider the commands:
graph mygraph.area(s) series1 series2 series3
mygraph.setelem(1) fcolor(blue) hatch(fdiagonal) gray(6)
mygraph.setelem(1) fcolor(0, 0, 255) hatch(fdiagonal) gray(6)

The first command creates MYGRAPH, a stacked area graph of SERIES1, SERIES2, and
SERIES3. The latter two commands are equivalent, modifying the first series by setting its
fill color to blue with a forward diagonal hatch. If MYGRAPH is viewed without color, the
area will appear with a hatched gray shade of index 6.

See Graph::setelem for a list of available color keywords, and for gray shade indexes and
available hatch keywords. Note that changes to gray shades will not be visible in the graph
unless color is turned off.
42—Chapter 2.Customizing a Graph

Using preset lines and fills


For your convenience, EViews provides you with a collection of preset line and fill character-
istics. Each line preset defines a color, width, pattern, and symbol for a line, and each fill
preset defines a color, gray shade, and hatch pattern for a fill. There are thirty line and thirty
fill presets.

The global graph options are initially set to use the EViews preset settings. These global
options are used when you first create a graph, providing a different appearance for each
line or fill. The first line preset is applied to the first data line, the second preset is applied to
the second data line, and so on. If your graph contains more than thirty lines or fills, the pre-
sets are simply reused in order.

You may customize the graph defaults in the global Graph Options dialog. Your settings will
replace the existing EViews defaults, and will be applied to all graphs created in the future.

EViews allows you to use either the original EViews presets, or those you have specified in
the global Graph Options dialog when setting the characteristics of an existing graph. The
keyword preset is used to indicate that you should use the set of options from the corre-
sponding EViews preset; the keyword default is used to indicate that you should use the
set of options from the corresponding global graph element defaults.

For example:
mygraph.setelem(2) preset(3)

allows the second fill area in MYGRAPH to use the original EViews presets for a third fill
area. In current versions of EViews, these settings include a green fill, a medium gray shade
of 8, and no hatch.

Alternatively:
mygraph.setelem(2) default(3)

also changes the second area of MYGRAPH, but uses the third set of user-defined presets. If
you have not yet modified your global graph defaults, the two commands will yield identical
results.

When using the preset or default keywords with boxplots, the line color of the specified
preset will be applied to all boxes, whiskers, and staples in the graph. See “Modifying Box-
plots” on page 52 for additional information.

Scaling and axes


There are four commands that may be used to modify the axis and scaling characteristics of
your graphs:
• First, the Graph::setelem command with the axis keyword may be used to assign
data elements to different axes.
Customizing a Graph—43

• Second, the Graph::axis command can be used to customize the appearance of any
axes in the graph object. You may employ the axis command to modify the scaling of
the data itself, for example, as when you use a logarithmic scale, or to alter the scaling
of the axis, as when you enable dual scaling. The axis command may also be used to
change the appearance of axes, such as to modify tick marks, change the font size of
axis labels, turn on grid or zero lines, or duplicate axes.
• Third, the Graph::datelabel command modifies the labeling of the bottom date/
time axis in time plots. Use this command to change the way date labels are formatted
or to specify label frequency.
• Finally, the Graph::setobslabel command may be used to create custom axis
labels for the observation scale of a graph.

Assigning data to an axis


In most cases, when a graph is created, all data elements are initially assigned to the left
axis. XY graphs differ slightly in that data elements are initially assigned to either the left or
bottom axis.

Once a graph is created, individual elements may generally be assigned to either the left or
right axis. In XY graphs, you may reassign individual elements to either the left, right, top,
or bottom axis, while in boxplots or stacked time/observation graphs all data elements must
be assigned to the same vertical axis.

To assign a data element to a different axis, use the setelem command with the axis key-
word. For example, the commands:
graph graph02.line ser1 ser2
graph02.setelem(2) axis(right)

first create GRAPH02, a line graph of SER1 and SER2, and then turn GRAPH02 into a dual
scaled graph by assigning the second data element, SER2, to the right axis.

In this example, GRAPH02 uses the default setting for dual scale graphs by disallowing
crossing, so that the left and right scales do not overlap. To allow the scales to overlap, use
the axis command with the overlap keyword, as in:
graph02.axis overlap

The left and right scales now span the entire axes, allowing the data lines to cross. To
reverse this action and disallow crossing, use -overlap, (the overlap keyword preceded
by a minus sign, “–”).

For XY graphs without pairing, the first series is generally plotted along the bottom axis, and
the remaining series are plotted on the left axis. XY graphs allow more manipulation than
time/observation plots, because the top and bottom axes may also be assigned to an ele-
ment. For example:
44—Chapter 2.Customizing a Graph

graph graph03.xyline s1 s2 s3 s4
graph03.setelem(1) axis(top)
graph03.setelem(2) axis(right)

first creates an XY line graph GRAPH03 of the series S1, S2, S3, and S4. The first series is
then assigned to the top axis, and the second series is moved to the right axis. Note that the
graph now uses three axes: top, left, and right.

Note that the element index in the setelem command is not necessary for boxplots and
stacked time/observation graphs, since all data elements must be assigned to the same ver-
tical axis.

While EViews allows dual scaling for the vertical axes in most graph types, the horizontal
axes must use a single scale on either the top or bottom axis. When a new element is moved
to or from one of the horizontal axes, EViews will, if necessary, reassign elements as
required so that there is a single horizontal scale.

For example, using the graph created above, the command:


graph03.setelem(3) axis(bottom)

moves the third series to the bottom axis, forcing the first series to be reassigned from the
top to the left axis. If you then issue the command:
graph03.setelem(3) axis(right)

EViews will assign the third series to the right axis as directed, with the first (next available
element, starting with the first) series taking its place on the horizontal bottom axis. If the
first element is subsequently moved to a vertical axis, the second element will take its place
on the horizontal axis, and so forth. Note that series will never be reassigned to the right or
top axis, so that series that placed on the top or right axis and subsequently reassigned will
not be replaced automatically.

For XY graphs with pairing, the same principles apply. However, since the elements are
graphed in pairs, there is a set of elements that should be assigned to the same horizontal
axis. You can switch which set is assigned to the horizontal using the axis keyword. For
example:
graph graph04.xypair s1 s2 s3 s4
graph03.setelem(1) axis(left)

creates an XY graph that plots the series S1 against S2, and S3 against S4. Usually, the
default settings assign the first and third series to the bottom axis, and the second and
fourth series to the left axis. The second command line moves the first series (S1) from the
bottom to the left axis. Since S1 and S3 are tied to the same axis, the S3 series will also be
assigned to the left axis. The second and fourth series (S2 and S4) will take their place on
the bottom axis.
Customizing a Graph—45

Modifying the data axis


The Graph::axis command may be used to change the way data is scaled on an axis. To
rescale the data, specify the axis you wish to change and use one of the following keywords:
linear, linearzero (linear with zero included in axis), log (logarithmic), norm (stan-
dardized). For example:
graph graph05.line ser1 ser2
graph05.axis(left) log

creates a line graph GRAPH05 of the series SER1 and SER2, and changes the left axis scaling
method to logarithmic.

The interaction of the data scales (these are the left and right axes for non-XY graphs) can
be controlled using axis with the overlap keyword. The overlap keyword controls the
overlap of vertical scales, where each scale has at least one series assigned to it. For
instance:
graph graph06.line s1 s2
graph06.setelem(2) axis(right)
graph06.axis overlap

first creates GRAPH06, a line graph of series S1 and S2, and assigns the second series to the
right axis. The last command allows the vertical scales to overlap.

The axis command may also be used to change or invert the endpoints of the data scale,
using the range or invert keywords:
graph05.axis(left) -invert range(minmax)

inverts the left scale of GRAPH05 (“–” indicates an inverted scale) and sets its endpoints to
the minimum and maximum values of the data.

Modifying the date/time axis


EViews automatically determines an optimal set of labels for the bottom axis of time plots. If
you wish to modify the frequency or date format of the labels, you should use the
Graph::datelabel command. Alternately, to create editable labels on the observation
scale, use the Graph::setobslabel command.

To control the number of observations between labels, use datelabel with the interval
keyword to specify a desired step size. The stand-alone step size keywords include: auto
(use EViews' default method for determining step size), ends (label first and last observa-
tions), and all (label every observation). For example,
mygraph.datelabel interval(ends)

labels only the endpoints of MYGRAPH. You may also use a step size keyword in conjunc-
tion with a step number to further control the labeling. These step size keywords include:
46—Chapter 2.Customizing a Graph

obs (one observation), year (one year), m (one month), and q (one quarter), where each
keyword determines the units of the number specified in the step keyword. For example, to
label every ten years, you may specify:
mygraph.datelabel interval(year, 10)

In addition to specifying the space between labels, you may indicate a specific observation
to receive a label. The step increment will then center around this observation. For example:
mygraph.datelabel interval(obs, 10, 25)

labels every tenth observation, centered around the twenty-fifth observation.

You may also use datelabel to modify the format of the dates or change their placement
on the axis. Using the format or span keywords,
mygraph02.datelabel format(yy) -span

formats the labels so that they display as two digit years, and disables interval spanning. If
interval spanning is enabled, labels will be centered between the applicable tick marks. If
spanning is disabled, labels are placed directly on the tick marks. For instance, in a plot of
monthly data with annual labeling, the labels may be centered over the twelve monthly
ticks (spanning enabled) or placed on the annual tick marks (spanning disabled).

If your axis labels require further customization, you may use the setobslabel command
to create a set of custom labels.
mygraph.setobslabel(current) "CA" "OR" "WA"

creates a set of axis labels, initializing each with the date or observation number and assigns
the labels “CA”, “OR”, and “WA” to the first three observations.

To return to EViews automatic labeling, you may use the clear option:
mygraph.setobslabel(clear)

Customizing axis appearance


You may customize the appearance of tick marks, modify label font size, add grid lines, or
duplicate axes labeling in your graph using Graph::axis.

Follow the axis keyword with a descriptor of the axis you wish to modify and one or more
arguments. For instance, using the ticksin, minor, and font keywords:
mygraph.axis(left) ticksin -minor font(10)

The left axis of MYGRAPH is now drawn with the tick marks inside the graph, no minor
ticks, and a label font size of 10 point.

To add lines to a graph, use the grid or zeroline keywords:


mygraph01.axis(left) -label grid zeroline
Customizing a Graph—47

MYGRAPH01 hides the labels on its left axis, draws horizontal grid lines at the major ticks,
and draws a line through zero on the left scale.

In single scale graphs, it is sometimes desirable to display the axis labels on both the left and
right hand sides of the graph. The mirror keyword may be used to turn on or off the dis-
play of duplicate axes. For example:
graph graph06.line s1 s2
graph06.axis mirror

creates a line graph with both series assigned to the left axis (the default assignment), then
turns on mirroring of the left axis to the right axis of the graph. Note that in the latter com-
mand, you need not specify an axis to modify, since mirroring sets both the left and right
axes to be the same.

If dual scaling is enabled, mirroring will be overridden. In our example, assigning a data ele-
ment to the right axis:
graph06.setelem(1) axis(right)

will override axis mirroring. Note that if element 1 is subsequently reassigned to the left
scale, mirroring will again be enabled. To turn off mirroring entirely, simply precede the mir-
ror keyword with a minus sign. The command:
graph06.axis -mirror

turns off axis mirroring.

Customizing the graph frame


The graph frame is used to set the basic graph proportions and display characteristics that
are not part of the main portion of the graph.

Graph size
The graph frame size and proportions may be modified using the Graph::options com-
mand. Simply specify a width and height using the size keyword. For example:
testgraph.options size(5,4)

resizes the frame of TESTGRAPH to 5  4 virtual inches.

Other frame characteristics


The Graph::options command may also be used to modify the appearance of the graph
area and the graph frame. A variety of modifications are possible.

First, you may change the background colors in your graph, by using the “fillcolor” and
“backcolor” keywords to change the frame fill color and the graph background color, respec-
tively. The graph proc command:
48—Chapter 2.Customizing a Graph

testgraph.options fillcolor(gray) backcolor(white)

fills the graph frame with gray, and sets the graph area background color to white. Here we
use the predefined color settings (“blue,” “red,” “ltred”, “green,” “black,” “white,” “pur-
ple,” “orange,” “yellow,” “gray,” “ltgray”); alternately, you may specify “color” with three
arguments corresponding to the respective RGB settings.

You may control display of axes frames. To select which axes should have a frame, you
should use the “frameaxes” keyword:
testgraph.options frameaxes(labeled)

which turns off the frame on any axis which is not associated with data. Similarly:
testgraph.options frameaxes(lb)

draws a frame on the left and bottom axes only.

By default, EViews uses the entire width of the graph for plotting data. If you wish to indent
the data display from the edges of the graph frame, you should use the “indenth” (indent
horizontal) or “indentv” (indent vertical) keywords:
testgraph.options indenth(.05) indentv(0.1)

indents the data by 0.05 inches horizontally, and 0.10 inches vertically from the edge of the
graph frame.

The options command also allows you to add and modify grid lines in your graph. For exam-
ple:
testgraph.options gridb -gridl gridpat(dash2) gridcolor(red)

turns on dashed, red, vertical gridlines from the bottom axis, while turning off left scale gri-
dlines.

Labeling data values


Bar and pie graphs allow you to label the value of your data within the graph. Use the
Graph::options command with one of the following keywords: barlabelabove, barla-
belinside, or pielabel. For example:
mybargraph.options barlabelabove

places a label above each bar in the graph indicating its data value. Note that the label will
be visible only when there is sufficient space in the graph.

Outlining and spacing filled areas


EViews draws a black outline around each bar or area in a bar or area graph, respectively. To
disable the outline, use options with the outlinebars or outlineareas keyword:
mybargraph.options -outlinebars
Customizing a Graph—49

Disabling the outline is useful for graphs whose bars are spaced closely together, enabling
you to see the fill color instead of an abundance of black outlines.

EViews attempts to place a space between each bar in a bar graph. This space disappears as
the number of bars increases. You may remove the space between bars by using the bar-
space keyword:
mybargraph.options -barspace

Modifying the Legend


A legend's location, text, and appearance may be customized. Note that single series graphs
and special graph types such as boxplots and histograms use text objects for labeling instead
of a legend. These text objects may only be modified interactively by double-clicking on the
object to bring up the text edit dialog.

To change the text string of a data element for use in the legend, use the Graph::name com-
mand:
graph graph06.line ser1 ser2
graph06.name(1) Unemployment
graph06.name(2) DMR

The first line creates a line graph GRAPH06 of the series SER1 and SER2. Initially, the legend
shows “SER1” and “SER2”. The second and third command lines change the text in the leg-
end to “Unemployment” and “DMR”.

Note that the name command is equivalent to using the Graph::setelem command with
the legend keyword. For instance,
graph06.setelem(1) legend(Unemployment)
graph06.setelem(2) legend(DMR)

produces the same results.

To remove a label from the legend, you may use name without providing a text string:
graph06.name(2)

removes the second label “DMR” from the legend.

For an XY graph, the name command modifies any data elements that appear as axis labels,
in addition to legend text. For example:
graph xygraph.xy ser1 ser2 ser3 ser4
xygraph.name(1) Age
xygraph.name(2) Height

creates an XY graph named XYGRAPH of the four series SER1, SER2, SER3, and SER4.
“SER1” appears as a horizontal axis label, while “SER2,” “SER3,” and “SER4” appear in the
50—Chapter 2.Customizing a Graph

legend. The second command line changes the horizontal label of the first series to “Age”.
The third line changes the second series label in the legend to “Height”.

To modify characteristics of the legend itself, use Graph::legend. Some of the primary
options may be set using the inbox, position and columns keywords. Consider, for exam-
ple, the commands:
graph graph07.line s1 s2 s3 s4
graph07.legend -inbox position(botleft) columns(4)

The first line creates a line graph of the four series S1, S2, S3, and S4. The second line
removes the box around the legend, positions the legend in the bottom left corner of the
graph window, and specifies that four columns should be used for the text strings of the leg-
end.

When a graph is created, EViews automatically determines a suitable number of columns for
the legend. A graph with four series, such as the one created above, would likely display two
columns of two labels each. The columns command above, with an argument of four, cre-
ates a long and slender legend, with each of the four series in its own column.

You may also use the legend command to change the font size or to disable the legend
completely:
graph07.legend font(10)
graph07.legend -display

Note that if the legend is hidden, any changes to the text or position of the legend remain,
and will reappear if the legend is displayed again.

Adding text to the graph


Text strings can be placed anywhere within the graph window. Using the Graph::addtext
command:
graph07.addtext(t) Fig 1: Monthly GDP

adds the text “Fig 1: Monthly GDP” to the top of the GRAPH07 window. You can also use
specific coordinates to specify the position of the upper left corner of the text. For example:
graph08.addtext(.2, .1, x) Figure 1

adds the text string “Figure 1” to GRAPH08. The text is placed 0.2 virtual inches in, and 0.1
virtual inches down from the top left corner of the graph frame. The “x” option instructs
EViews to place the text inside a box.

An existing text object can be edited interactively by double-clicking on the object to bring
up a text edit dialog. The object may be repositioned by specifying new coordinates in the
dialog, or by simply dragging the object to its desired location.
Customizing a Graph—51

Adding lines and shading


You may wish to highlight or separate specific areas of your graph by adding a line or
shaded area to the interior of the graph using the Graph::draw command. Specify the type
of line or shade option (line or shade), which axis it should be attached to (left, right,
bottom, top) and its position. For example:
graph09.draw(line, left) 5.2

draws a horizontal line at the value 5.2 on the left axis. Alternately:
graph09.draw(shade, left) 4.8 5.6

draws a shaded horizontal area bounded by the values 4.8 and 5.6 on the left axis. You can
also specify color, line width, and line pattern:
graph09.draw(line, bottom, color(blue), width(2), pattern(3))
1985:1

draws a vertical blue dashed line of width two points at the date “1985:1” on the bottom
axis. Color may be specified using one or more of the following options: color(n1, n2, n3),
where the arguments correspond to RGB settings, or color(keyword), where keyword is
one of the predefined color keywords (“blue”, “red”, “ltred”, “green”, “black”, “white”,
“purple”, “orange”, “yellow”, “gray”, “ltgray”).

Using graphs as templates


After customizing a graph as described above, you may wish to use your custom settings in
another graph. Using a graph template allows you to copy the graph type, line and fill set-
tings, axis scaling, legend attributes, and frame settings of one graph into another. This
enables a graph to adopt all characteristics of another graph—everything but the data itself.
To copy custom line or fill settings from the global graph options, use the preset or
default keywords of the Graph::setelem command (as described in “Using preset lines
and fills” on page 42).

Modifying an existing graph


To modify a named graph object, use the template command:
graph10.template customgraph

This command copies all the appearance attributes of CUSTOMGRAPH into GRAPH10.

To copy text labels, lines and shading in the template graph in addition to all other option
settings, use the “t” option:
graph10.template(t) customgraph

This command copies any text or shading objects that were added to the template graph
using the Graph::addtext or Graph::draw commands or the equivalent steps using dia-
52—Chapter 2.Customizing a Graph

logs. Note that using the “t” option overwrites any existing text and shading objects in the
target graph.

Using a template during graph creation


All graph type commands also provide a template option for use when creating a new graph.
For instance:
graph mygraph.line(o = customgraph) ser1 ser2

creates the graph MYGRAPH of the series SER1 and SER2, using CUSTOMGRAPH as a tem-
plate. The “o” option instructs EViews to copy all but the text, lines, and shading of the tem-
plate graph. To include these elements in the copy, use the “t” option in place of the “o”
option.

When used as a graph procedure, this method is equivalent to the one described above for
an existing graph, so that:
graph10.template(t) customgraph
graph10.bar(t = customgraph)

produce the same results.

Arranging multiple graphs


When you create a multiple graph, EViews automatically arranges the graphs within the
graph window. (See “Creating a Graph” on page 33 for information on how to create a mul-
tiple graph.) You may use either the “m” option during graph creation or the merge com-
mand.

To change the placement of the graphs, use the Graph::align command. Specify the num-
ber of columns in which to place the graphs and the horizontal and vertical space between
graphs, measured in virtual inches. For example:
graph graph11.merge graph01 graph02 graph03
graph11.align(2, 1, 1.5)

creates a multiple graph GRAPH11 of the graphs GRAPH01, GRAPH02, and GRAPH03. By
default, the graphs are stacked in one column. The second command realigns the graphs in
two columns, with 1 virtual inch between the graphs horizontally and 1.5 virtual inches
between the graphs vertically.

Modifying Boxplots
The appearance of boxplots can be customized using many of the commands described
above. A few special cases and additional commands are described below.
Customizing a Graph—53

Customizing lines and symbols


As with other graph types, the setelem command can be used with boxplots to modify line
and symbol attributes, assign the boxes to an axis, and use preset and default settings. To
use the Graph::setelem command with boxplots, use a box element keyword after the
command. For example:
boxgraph01.setelem(mean) symbol(circle)

changes the means in the boxplot BOXGRAPH01 to circles. Note that all boxes within a sin-
gle graph have the same attributes, and changes to appearance are applied to all boxes. For
instance:
boxgraph01.setelem(box) lcolor(orange) lpat(dash1) lwidth(2)

plots all boxes in BOXGRAPH01 with an orange dashed line of width 2 points. Also note that
when shaded confidence intervals are used, a lightened version of the box color will be used
for the shading. In this way, the above command also changes the confidence interval shad-
ing to a light orange.

Each element in a boxplot is represented by either a line or symbol. EViews will warn you if
you attempt to modify an inappropriate option (e.g., modifying the symbol of the box).

Assigning boxes to an axis


The setelem command may also be used to assign the boxes to another axis:
boxgraph01.setelem axis(right)

Note that since all boxes are assigned to the same axis, the index argument specifying a
graph element is not necessary.

Using preset line colors


During general graph creation, lines and fills take on the characteristics of the user-defined
presets. When a boxplot is created, the first user-defined line color is applied to the boxes,
whiskers, and staples. Similarly, when you use the preset or default keywords of the
setelem command with a boxplot, the line color of the preset is applied to the boxes, whis-
kers, and staples. (See “Using preset lines and fills” on page 42 for a description of presets.)

The preset and default methods work just as they do for other graph types, although
only the line color is applied to the graph. For example:
boxgraph01.setelem default(3)

applies the line color of the third user-defined line preset to the boxes, whiskers, and staples
of BOXGRAPH01. Note again that setelem does not require an argument specifying an
index, since the selected preset will apply to all boxes.
54—Chapter 2.Labeling Graphs

There are a number of setelem arguments that do not apply to boxplots. The fillcolor,
fillgray, and fillhatch option keywords are not available, as there are no custom areas
to be filled. The legend keyword is also not applicable, as boxplots use axis text labels in
place of a legend.

Hiding boxplot elements


In addition to the setelem command, boxplots provide a Graph::setbpelem command
for use in enabling or disabling specific box elements. Any element of the boxplot can be
hidden, except the box itself. Use the command with a list of box elements to show or hide.
For example:
boxgraph01.setbpelem -mean far

hides the means and confirms that the far outliers are shown in BOXGRAPH01.

Modifying box width and confidence intervals


The width of the individual boxes in a boxplot can be drawn in three ways: fixed width over
all boxes, proportional to the sample size, or proportional to the square root of the sample
size. To specify one of these methods, use the setbpelem command with the width key-
word, and one of the supported types (fixed, rootn, n). For example:
boxgraph01.setbpelem width(rootn)

draws the boxes in BOXGRAPH01 with widths proportional to the square root of their sam-
ple size.

There are three methods for displaying the confidence intervals in boxplots. They may be
notched, shaded, or not drawn at all, which you may specify using one of the supported
keywords (notch, shade, none). For example:
boxgraph01.setbpelem ci(notch)

draws the confidence intervals in BOXGRAPH01 as notches.

Labeling Graphs
As with all EViews objects, graphs have a label view to display and edit information such as
the graph name, last modified date, and remarks. To modify or view the label information,
use the Graph::label command:
graph12.label(r) Data from CPS 1988 March File

This command shows the label view, and the “r” option appends the text “Data from CPS
1988 March File” to the remarks field of GRAPH12.

To return to the graph view, use the graph keyword:


graph12.graph
Exporting Graphs to Files—55

All changes made in label view will be saved when the graph is saved.

Printing Graphs
A graph may be printed using the print (p. 566) command. For example:
print graph11 graph12

prints GRAPH11 and GRAPH12 on a single page.

In addition, many graph commands and graph views of objects include a print option. For
example, you can create and simultaneously print a line graph GRA1 of SER1 using the “p”
option:
graph gra1.line(p) ser1

You should check the individual commands for availability of this option.

Exporting Graphs to Files


You may use the Graph::save proc of a graph object to save the graph as a Windows meta-
file (.wmf), Enhanced Windows metafile (.emf), PostScript file (.eps), bitmap (.bmp),
Graphics Interchange Format (.gif), Joint Photographics Exchange Group (.jpg), Portable
Network Graphics (.png), LaTeX (.tex), Markdown (.md), or Moving Picture Experts Group-
4 (.mp4) file.

You must specify a file name and file type, and may also provide the file height, width, units
of measurement, and color use. PostScript files also allow you to save the graph with or
without a bounding box and to specify portrait or landscape orientation. For instance:
graph11.save(t=postscript, u=cm, w=12, -box) MyGraph1

saves GRAPH11 in the default directory as a PostScript file “MyGraph1.EPS”, with a width of
12 cm and no bounding box. The height is determined by holding the aspect ratio of the
graph constant. Similarly:
graph11.save(t=emf, u=pts, w=300, h=300, -c) c:\data\MyGraph2

saves GRAPH11 as an Enhanced Windows metafile “Mygraph2.EMF”. The graph is saved in


black and white, and scaled to 300  300 points.
graph11.save(t=png, u=in, w=5, d=300) MyGraph3

saves GRAPH11 in the default directory as a PNG file “Mygra3.PNG”. The image will be 5
inches wide at 300 dpi.
graph11.save(t=gif, u=pixels, w=500) MyGraph4

saves GRAPH11 in a 500 pixel wide GIF file, “Mygraph4.GIF”.


56—Chapter 2.Graph Summary

Graph Summary
See “Graph” on page 368 of the Object Reference for a full listing of procs that may be used
to customize graph objects, and for a list of the graph type commands.

Graph commands are documented in “Graph Creation Command Summary” on page 1266
of the Object Reference.
Chapter 3. Working with Tables and Spreadsheets

There are three types of tables in EViews: tabular views, which are tables used in the display
of views of other objects, named table objects, and unnamed table objects. The main portion
of this discussion focuses on the use of commands to customize the appearance of named
table objects. The latter portion of the chapter describes the set of tools that may be used to
customize the display characteristics of spreadsheet views of objects (see “Customizing
Spreadsheet Views,” beginning on page 74).

You may use EViews commands to generate custom tables of formatted output from your
programs. A table object is an object made up of rows and columns of cells, each of which
can contain either a number or a string, as well as information used to control formatting for
display or printing.

Chapter 17. “Table and Text Objects,” on page 937 of the Object Reference describes various
interactive tools for customizing table views and objects.

Creating a Table
There are two basic ways to create a table object: by freezing an object view, or by issuing a
table declaration.

Creating Tables from an Object View


You may create a table object from another object, by combining an object view command
with the freeze (p. 457) command. Simply follow the freeze keyword with an optional
name for the table object, and the tabular view to be frozen. For example, since the com-
mand
grp6.stats

displays the statistics view of the group GRP6, the command


freeze(mytab) grp6.stats

creates and displays a table object MYTAB containing the contents of the previous view.

You should avoid creating unnamed tables when using commands in programs since you
will be unable to refer to, or work with the resulting object using commands. If the MYTAB
option were omitted in the previous example, EViews would create and display an untitled
table object. This table object may be customized interactively, but may not be referred to in
programs. You may, of course, assign a name to the table interactively.

Once you have created a named table object, you may use the various table object procs to
further customize the appearance of your table. See “Customizing Tables,” beginning on
page 60.
58—Chapter 3.Assigning Table Values

Declaring Tables
To declare a table, indicate the number of rows and columns and provide a valid name. For
example:
table(10,20) bestres

creates a table with 10 rows and 20 columns named BESTRES. You can change the size of a
table by declaring it again. Re-declaring the table to a larger size does not destroy the con-
tents of the table; any cells in the new table that existed in the original table will contain
their previous values.

Tables are automatically resized when you attempt to fill a table cell outside the table’s cur-
rent dimensions. This behavior is different from matrix objects which issue an error when
an out-of-range element is accessed.

Assigning Table Values


You may modify the contents of cells in a table using assignment statements. Each cell of the
table can be assigned either a string or a numeric value.

Assigning Strings
To place a string value into a table cell, follow the table name by a cell location (row and
column pair in parentheses), then an equal sign and a string expression.

For example:
table bestres
bestres(1,6) = "convergence criterion"
%strvar = "lm test"
bestres(2,6) = %strvar
bestres(2,6) = bestres(2,6) + " with 5 df"

creates the table BESTRES and places various string values into cells of the table.

Assigning Numbers
Numbers can be entered directly into cells, or they can be converted to strings before being
placed in the table.

Unless there is a good reason to do otherwise, we recommend that numbers be entered


directly into table cells. If entered directly, the number will be displayed according to the
numerical format set for that cell; if the format is changed, the number will be redisplayed
according to the new format. If the number is first converted to a string, the number will be
frozen in that form and cannot be reformatted to a different precision.

For example:
Assigning Table Values—59

table tab1
tab1(3,4) = 15.345
tab1(4,2) = 1e-5
!ev = 10
tab1(5,1) = !ev
scalar f = 12345.67
tab1(6,2) = f

creates the table TAB1 and assigns numbers to various cells.

Assignment with Formatting


The setcell (p. 585) command is like direct cell assignment in that it allows you to set the
contents of a cell, but setcell also allows you to provide a set of simple formatting options
for the cell. If you desire even greater control over formatting, or if you wish to alter the for-
mat of a cell without altering its contents, you should use the tools outlined in “Customizing
Tables,” beginning on page 60.

The setcell command takes the following arguments:


• the name of the table
• the row and the column of the cell
• the number or string to be placed in the cell
• (optionally) a justification code or a numerical format code, or both

The justification codes are:


• “c” for centered (default)
• “r” for right-justified
• “l” for left-justified

The numerical format code determines the format with which a number in a cell is dis-
played; cells containing strings will be unaffected. The format code can either be a positive
integer, in which case it specifies the number of digits to be displayed after the decimal
point, or a negative integer, in which case it specifies the total number of characters to be
used to display the number. These two cases correspond to the fixed decimal and fixed
character fields in the number format dialog.

Note that when using a negative format code, one character is always reserved at the start of
a number to indicate its sign, and if the number contains a decimal point, that will also be
counted as a character. The remaining characters will be used to display digits. If the num-
ber is too large or too small to display in the available space, EViews will attempt to use sci-
60—Chapter 3.Customizing Tables

entific notation. If there is insufficient space for scientific notation (six characters or less),
the cell will contain asterisks to indicate an error.

Some examples of using setcell:


setcell(tabres,9,11,%label)

puts the contents of %LABEL into row 9, column 11 of the table TABRES.
setcell(big_tabl,1,1,%info,"c")

inserts the contents of %INFO in BIG_TAB1(1,1), and displays the cell with centered justifi-
cation.
setcell(tab1,5,5,!data)

puts the number !DATA into cell (5,5) of table TAB1, with default numerical formatting.
setcell(tab1,5,6,!data,4)

puts the number !DATA into TAB1, with 4 digits to the right of the decimal point.
setcell(tab1,3,11,!data,"r",3)

puts the number !DATA into TAB1, right-justified, with 3 digits to the right of the decimal
point.
setcell(tab1,4,2,!data,-7)

puts the number in !DATA into TAB1, with 7 characters used for display.

Customizing Tables
EViews provides considerable control over the appearance of table objects, providing a vari-
ety of table procedures allowing you specify row heights and column widths, content for-
matting, justification, font face, size, and color, cell background color and borders. Cell
merging and annotation are also supported.

Column Width and Row Height


We begin by noting that if the contents of a cell are wider or taller than the display width or
height of the cell, part of the cell contents may not be visible. You may use the
Table::setwidth and Table::setheight table procedures to change the dimensions of
a column or row of table cells.

To change the column widths for a set of columns in a table, use the setwidth keyword fol-
lowed by a column range specification in parentheses, and a desired width.

The column range should be either a single column number or letter (e.g., “5”, “E”), a colon
delimited range of columns (from low to high, e.g., “3:5”, “C:E”), or the keyword “@ALL”.
The width unit is computed from representative characters in the default font for the current
table (the EViews table default font at the time the table was created), and corresponds
Customizing Tables—61

roughly to a single character. Width values may be non-integer values with resolution up to
1/10 of a unit. The default width value for columns in an unmodified table is 10.

For example, both commands


tab1.setwidth(2) 12
tab1.setwidth(B) 12

set the width of column 2 to 12 width units, while the command


tab1.setwidth(2:10) 20

sets the widths for columns 2 through 10 to 20 width units. To set all of the column widths,
use the “@ALL” keyword.
tab1.setwidth(@all) 20

Similarly, you may specify row heights using the setheight keyword, followed by a row
specification in parentheses, and a desired row height.

Rows are specified either as a single row number (e.g., “5”), as a colon delimited range of
rows (from low to high, e.g., “3:5”), or using the keyword “@ALL”. Row heights are given in
height unit values, where height units are in character heights. The character height is given
by the font-specific sum of the units above and below the baseline and the leading in the
default font for the current table. Height values may be non-integer values with resolution
up to 1/10 of a height unit. The default row height value is 1.

For example,
tab1.setheight(2) 1

sets the height of row 2 to match the table default font character height, while
tab1.setheight(2) 3.5

increases the row height to 3-1/2 character heights.

Similarly, the command:


tab1.setheight(2:7) 1.5

sets the heights for rows 2 through 7 to 1-1/2 character heights.

We may set the row height conditionally. The command


tab1.setheight(2:7 if [a2:a7]>0.5) 1.5

will set the heights of row 2 through 7 to 1-1/2 character heights if the additional condition
is true. In this case, if the value of cell A2 is greater than 0.5, the height of row will be set to
1.5 character. If the value of cell A3 is greater than 0.5, the height of row 3 will be set to 1.5
character and so forth through row 7. For more information on using table ranges and
expressions see “Conditional Table Cells” on page 68.
62—Chapter 3.Customizing Tables

Lastly the command,


tab1.setheight(@all) 2

sets all row heights to twice the default height.

Earlier versions of EViews supported the setting of column widths using the setcolwidth
command. This command, which is provided for backward compatibility, offers only a sub-
set of the capabilities of Table::setwidth.

Cell Formatting
A host of cell characteristics may be set using table procedures. Each procedure is designed
to work on individual cells, ranges of cells, or the entire table.

Content Formatting
Cell content formatting allows you to alter the appearance of the data in a table cell without
changing the contents of the cell. Using the table proc Table::setformat, you may, for
example, instruct EViews to change the format of a number to scientific or fixed decimal, or
to display a date number in a different date format. These changes in display format do not
alter the cell values.

To format the contents of table cells, simply follow the table name with a period and the
setformat proc keyword, followed by a cell range specification in parentheses, and then a
valid numeric or date format string. The cell range may be specified in a number of ways,
including individual cells, cell rectangles, row or column ranges or the entire table. See
Table::setformat for a description of cell range specification and numeric and date for-
mat string syntax.

For example, to set the format for the fifth column of a matrix to fixed 5-digit precision, you
may provide the format specification:
tab1.setformat(e) f.5

To set a format for the cell in the third row of the fifth column to scientific notation with 5
digits of precision, specify the individual cell, as in:
tab1.setformat(3,e) e.5
tab1.setformat(e3) e.5

To specify the format for a rectangle of cells, specify the upper left and lower right cells in
the rectangle. The following commands set cells in the same region to show 3-significant
digits, with negative numbers in parentheses:
tab1.setformat(2,B,10,D) g(.3)
tab1.setformat(r2c2:r10c4) g(.3)
tab1.setformat(b2:d10) g(.3)

The rectangle of cells is delimited by row 2, column 2, and row 10, column 4.
Customizing Tables—63

To conditionally set the format of cells, you can provide a conditional cell range argument.
For example, using the following 2 commands in sequence
tab1.setformat(r2c2:r10c4 if [r2c2:r10c4]<10000) g(.2)
tab1.setformat(r2c2:r10c4 if [r2c2:r10c4]<1000) g(.3)

will set the format of cells row 2, column 2, to row 10, column 4 based on their cell values.
If the cell values are less than 10000 only 2 significant digits will be displayed but if the cell
values are less than 1000, 3 significant digits will be displayed. For more information on
using table ranges and expressions see “Conditional Table Cells” on page 68.

Alternately you may provide a date format for the table cells. The command:
tab1.setformat(@all) "dd/MM/YY HH:MI:SS.SSS"

will display numeric values in the entire table using formatted date strings containing days
followed by months, years, hours, minutes and seconds, to a resolution of thousandths of a
second.

Note that changing the display format of a cell that contains a string will have no effect
unless the cell is later changed to contain a numerical value.

Justification and Indentation


The cell justification and indentation control the position of the table cell contents within
the table cell itself.

You may use the Table::setjust proc to position the cell contents in the cell. Simply use
the setjust keyword, followed by a cell range specification in parentheses, and one or
more keywords describing a vertical or horizontal position for the cell contents. You may use
the keywords auto, left, right, and center to control horizontal positioning, and top,
middle, and bottom to control vertical positioning. You may use the auto keyword to spec-
ify left justification for string cells and right justification for numeric cells.

For example,
tab1.setjust(@all) top left

sets the justification for all cells in the table to top left, while
tab1.setjust(2,B,10,D) center

horizontally centers the cell contents in the rectangle from B2 to D10, while leaving the ver-
tical justification unchanged.

In addition, you may use Table::setindent to specify a left or right indentation from the
edge of the cell for cells that are left or right justified, respectively. You should use the
setindent keyword followed by a cell range in parentheses, and an indentation unit, spec-
ified in 1/5 of a width unit. Indentation is only relevant for non-center justified cells.
64—Chapter 3.Customizing Tables

For example:
tab1.setjust(2,B,10,D) left
tab1.indent(2,B,10,D) 2

left-justifies, then indents the specified cells by 2/5 of a width unit from the left-hand side of
the cell.

It may be useful to adjust the justification based on the contents of the cell. To change verti-
cal justification based on the length of the string cell in the cell you could use a conditional
range. For example,
tab1.setjust(b2:d10 if @length([b2:d10])>15) top

will individually set the vertical justification to be top justified for cells b2 through d10 if the
cells contain a string longer than 15. For more information on using table ranges and expres-
sions see “Conditional Table Cells” on page 68.

Alternatively,
tab2.setjust(@all) center
tab2.indent(@all) 3

will set the indentation for all cells in the table to 3/5 of a width unit, but this will have no
effect on the center justified cells. If the cells are later modified to be left or right justified,
the indentation will be used. If you subsequently issue the command
tab2.indent(@all) right

the cells will be indented 3/5 of a width unit from the right-hand edges.

Fonts
You may specify font face and characteristics, and the font color for table cells using the
Table::setfont and Table::settextcolor table procs.

The setfont proc should be used to set the font face, size, boldface, italic, strikethrough
and underline characteristics for table cells. You should provide a cell range specification,
and one or more font arguments corresponding to font characteristics that you wish to mod-
ify. For example:
tab1.setfont(3,B,10,D) "Times New Roman" +u 8pt

changes the text in the specified cells to Times New Roman, 8 point, underline. Similarly,
tab1.setfont(4,B) -b +i -s

adds the italic to and removes boldface and strikethrough from the B4 cell.

To set the color of your text, use settextcolor with a cell range specification and a color
specification. Color specifications may be provided using the @RGB or @HEX settings, or
using one of the EViews predefined colors keywords:
Customizing Tables—65

tab1.settextcolor(f2:g10) @rgb(255, 128, 0)


tab1.settextcolor(f2:g10) orange

sets the text color for the specified cells to orange.

See Table::setfillcolor for a complete description of color specifications.

One practical text coloring application is to highlight negative cell values in a table by
changing the text color. Using settextcolor, you may use a colormap (see “Value-Based
Text and Fill Coloring” on page 186 in User’s Guide I) or you can manually set the text color
with a Boolean expression.

To set the text color of negative values in your table for the cell range A1:G10, you can either
use a positive-negative colormap,
tab1.settextcolor(t=posneg, A1:G10) posclr(@RGB(0,0,0))
negclr(@RGB(255,0,0))naclr(@RGB(0,0,0))

or manually set the text color via


tab1.settextcolor(A1:G10 if [A1:G10]<0) red

For more information on using table ranges and expressions see“Conditional Table Cells” on
page 68.

(Note that both commands set negative values to red. The difference between the two meth-
ods is colormaps dynamically determines the text color during rendering. Therefore, if the
cell value is changed so will the color. Whereas when manually setting the text color, the
color becomes fixed and will not change regardless of the cell value. While the use of color-
maps is more flexible and dynamic, defining a colormap is more difficult. Manually setting
the color is easier and faster and recommended when the cell values in the table are not
expected to change.)

Background and Borders


You may set the background color for cells using the Table::setfillcolor table proce-
dure. Specify the cell range and provide a color specification using @RGB or @HEX settings
or one of the predefined color keywords. The commands:
tab1.setfillcolor(R2C3:R3C6) ltgray
tab1.setfillcolor(2,C,3,F) @rgb(192, 192, 192)

both set the background color of the specified cells to light gray.

The Table::setlines table proc may be used to draw borders or lines around specified
table cells. If a single cell is specified, you may draw borders around the cell or a double line
through the center of the cell. If multiple columns or rows is selected, you may, in addition,
add borders between cells.
66—Chapter 3.Customizing Tables

Follow the name of the table object with a period, the setlines keyword, a cell range spec-
ification, and one or more line arguments describing the lines and borders you wish to draw.
For example:
tab1.setlines(b2:d6) +a -h -v

first adds all borders (“a”) to the cells in the rectangle defined by B2 and D6, then removes
the inner horizontal (“h”), and inner vertical (“v”) borders. The command
tab1.setlines(2,b) +o

adds borders to the outside (“o”), all four borders, of the B2 cell.

You may also use the setlines command to place double horizontal separator lines in the
table. Enter the setlines keyword, followed by the name of the table, and a row number,
both in parentheses. For example,
bestres.setlines(8) +d

places a separator line in the eighth row of the table BESTRES. The command:
bestres.setlines(8) -d

removes the double separator lines from all of the cells in the eighth row of the table.

You may also apply a conditional expression when activating borders. Let’s assume we have
a table that contains quarterly data by row, whereby the first column has the date (similar to
a series spreadsheet) and we would like to visually indicate the starts and ends of years. We
will accomplish this effect by applying a conditional expression to add a bottom border to
the rows which contain the fourth quarter.

By default, quarterly workfile dates in EViews are denoted by year followed by quarter. The
fourth quarter of the 2020 would appear as ‘2020Q4’. With this information, we can use the
command:
tab1.setlines(a1:d50 if @right([a1:a50], 2)=="Q4")

This command will add, for each row from 1 to 50, a bottom border from column A to D if
the first cell in their respective row ends in “Q4”. For more information on using table ranges
and expressions see “Conditional Table Cells” on page 68.

Cell Annotation and Merging


Each cell in a table object is capable of containing a comment. Cell comments contain text
that is hidden until the mouse cursor is placed over the cell containing the comment. Com-
ments are useful for adding notes to a table without changing the appearance of the table.

To add a comment with the Table::comment table proc, follow the name of the table
object with a period, a single cell identifier (in parentheses), and the comment text enclosed
Customizing Tables—67

in double quotes. If no comment text is provided, a previously defined comment will be


removed.

To add a comment “hello world” to the cell in the second row, fourth column, you may use
the command:
tab1.comment(d2) "hello world"

To remove the comment simply repeat the command, omitting the text:
tab1.comment(d2)

In addition, EViews permits you to merge cells horizontally in a table object. To merge mul-
tiple cells in a row or to un-merge previously merged cells, you should use the
Table::setmerge table proc. Enter the name of the table object, a period, followed by a
cell range describing the cells in a single row that are to be merged.

If the first specified column is less than the last specified column (left specified before right),
the cells in the row will be merged left to right, otherwise, the cells will be merged from
right to left. The contents of the merged cell will be taken from the first cell in the merged
region. If merging from left to right, the leftmost cell contents will be used; if merging from
right to left, the rightmost cell contents will be displayed.

For example,
tab1.setmerge(a2:d2)

merges the cells in row 2, columns 1 to 4, from left to right, while


tab2.setmerge(d2:a2)

merges the cells in row 2, columns 2 to 5, from right to left. The cell display will use the left-
most cell in the first example, and the rightmost in the second.

If you specify a merge involving previously merged cells, EViews will unmerge all cells
within the specified range. We may then unmerge cells by issuing the Table::setmerge
command using any of the previously merged cells. The command:
tab2.setmerge(r2c4)

unmerges the previously merged cells.

When modifying a characteristic of a table via command, the section of the table to be mod-
ified must be specified. This section or range can be a set of cells, rows, or columns. You
could for example the set fill color of row or column or rectangular area within the table. It
may also be desirable to set remove a row or delete a column. EViews has numerous com-
mands for customizing a table.
68—Chapter 3.Customizing Tables

Conditional Table Cells


Many EViews table customization procedures allow you to specify ranges of cells. For exam-
ple, Table::setfillcolor allows you to specify the background color for the specified
cells, while Table::setformat allows you to apply custom formatting to the contents of
the specified cells.

There are cases when you may wish to perform operations on cells in a table, but only under
certain conditions. Suppose, for example, that you have a table with annual data on each
row and you want to identify each row where there is a decrease in value in column 3 when
compared to the value for the previous row (year). The goal is to apply custom text or cell
formatting to these rows.

Fortunately, EViews allows you to identify the desired cells using a conditional target range
specification comprised of a target_range and a boolean_expression. You may specify the con-
ditional target cells using the syntax:
target_range if boolean_expression

where target_range gives the range of potential cells of interest, “if” is a keyword, and bool-
ean_expression provides indicators for which of the target_range cells to use.

Similarly, the table @find data member (“Table Data Members” on page 1073 of Object Ref-
erence) allows you to obtain a string list containing the cells in a table range that satisfy a
condition.

The syntax for @find requires a find_expression:


table_name.@find(find_expression)
where find_expression simultaneously specifies the range of cells to consider and the boolean
expression for whether each cell should be used.

Note that in contrast to the conditional target syntax above, @find does not require an
explicit target_specification since the find_expression implicitly defines the range of cells to
consider.

Target Range Specification


The target_range of potential cells to consider consists of the rectangle of cells defined by
first_cell and last_cell:
first_cell:last_cell
where first_cell and last_cell are cell identifiers (separated by “:”) specified using either a col-
umn letter and row number (e.g., “A2”), or using “R” (for row) followed by the row number fol-
lowed by “C” (for column) and the column number (e.g., “R1C2”).

You may also use the special keyword “@all” to refer to every cell in the table.
Customizing Tables—69

It is useful to consider simple examples of an unconditional target_range in action. Suppose


that we wish to set the fill color for a collection of cells. The command
tab1.setfillcolor(A2:A7) red

will set the fill color of all the cells in the target region from A2 (top left cell) to A7 (bottom
right cell) in table TAB1 to red. In this case, the target cell range is “A2:A7” and EViews will
set the fill color for every cell from A2 to A7 to red.

Similarly,
tab1.setfillcolor(@all) red

sets the background color in all of cells of the table to red.

Boolean Expression
The boolean_expression defines a comparison producing indicators corresponding to the ele-
ments of the target_range.

Basic Comparisons
The boolean_expression syntax consists of
left_spec “operator” right_spec
where “operator” is a standard EViews comparison operator such as “>”, “<>” “<=”,
“=”, etc., and where the left_spec and right_spec consist of one of:
• a literal value, e.g., the number 37, or the string “Kansas” or “New Mexico”.
• a cell range, enclosed in “[]”, e.g. “[A1:C9]”, “[R1C1:R10C30]”.

where for purposes of the boolean comparison, the cell range is refers to the contents of the
corresponding cells in the table.

For example, for a target_range of size 5  3 we may specify the boolean_expressions:


[A1:C5] < 3
[A1:C5] = [B1:B5]
[C2] > [A1:C1]
[E1:E5] <> "Out of Stock"

where we see that the specs can be rectangles, columns, and rows of cells, literal numbers,
and literal strings.

Conceptually, EViews takes the left_spec and creates an implicit table of values that is the
same size as target_range, then compares it to a similarly constructed table of right_spec val-
ues. The pairwise comparison of the cells of the two implicit tables produces the boolean
indicators for the conditional target range.

The rules for forming the implicit tables are straightforward:


70—Chapter 3.Customizing Tables

• if the spec is a numeric or string literal, or a single cell, the value will be repeated for
each element of the implicit table
• if spec is a row of cells, it must have the same number of columns as target_range; the
values in spec will be repeated for each row of the implicit table
• if the spec is a column of cells, it must have the same number of rows as target_range;
the values in spec will be repeated for each column of the implicit table
• if the spec is a rectangle of cells, it must be of the same dimension as target_range; the
implicit table uses the values in spec

These concepts are most easily illustrated via examples, in which we assume a 5  3
target_range.

The boolean comparison,


[A1:C5] < 3

compares every element of


• the 5  3 rectangle of the values in the table cells from A1 to C5
• (an implicit 5  3 table of) the number 3

producing a TRUE if an element of the former is less than the latter, and a FALSE otherwise.
[A1:C5] = [B1:B5]

compares every element of


• the 5  3 rectangle of the values in the table cells from A1 to C5
• an implicit 5  3 table constructed by repeating horizontally the column of values in
B1 to B5

producing a TRUE if an element of the former is equal to the latter, and a FALSE otherwise.
[C2] > [A1:C1]

compares every element of


• (a 5  3 implicit table filled with the value in C2
• an implicit 5  3 table constructed by repeating vertically the row of values in A1 to
C1

producing a TRUE if an element of the former is greater than the latter, and a FALSE other-
wise.
[E1:E5] <> "Out of Stock"

compares every element of


Customizing Tables—71

• the 5  3 implicit table filled with the column of valuesin E1 to E5 repeated horizon-
tally
• (an implicit 5  3 table of) the string value “Out of Stock”

producing a TRUE if the element of the former is not equal to the latter, and a FALSE other-
wise.

We can illustrate the use boolean expressions by modifying our earlier command that
setfillcolor using an unconditional target_range. Suppose that we add an “if” condition,
for whether the cells are decreasing in value, to the earlier command. The command
tab1.setfillcolor(A2:A7 if [A2:A7]<[A1:A6]) red

will only set the fill color to red for the target cell range, if the decreasing value condition
holds.

Comparisons using Expressions


Earlier, we saw how to use the boolean_expression to define simple comparisons of cell val-
ues and literals (“Basic Comparisons” on page 69).

EViews expression and function language can be used with the numeric and string literals in
and cell expressions in left_spec and right_spec. We may have quite complicated boolean
expressions as in:
[A1:C5]^2+log(@pi*[A1:C5]) < 3
[A1:C5]/3 = [B1:B5]
@tdist([C2], [C4]) > [A1:C1]/100
@length([E1:E5]) <> "Out of Stock"

where a function or expression involving a cell range is interpreted as applying the function
or expression to each element of the range after expansion into implicit tables.

For the most part, interpreting the expressions is straightforward, as we can simply evaluate
the expressions for each element of the implicit tables. The power of this type of evaluation
can, however, lead to potentially useful but at first glance odd specifications, as in
tab1.setfillcolor(A1:B2 if @log([A1:A2]^2+[A1:B1])/10 <
@floor(3+[C1:D2])) red

While interpreting this expression without invoking the concept of implicit tables is quite
difficult, in practice, evaluation is reasonably straightforward:
1. the target_range is “A1:B2” which defines a 2  2 target and size for the implicit
tables
2. “[A1:A2]” is a 1  2 row range which is repeated vertically to yield a 2  2 implicit
table; each element of the table is squared
72—Chapter 3.Customizing Tables

3. “[A1:B1]” is a 2  1 column range which is repeated horizontally to yield a 2  2


implicit table; each element is divided by 10
4. the results in the previous two steps are added together cell-by-cell to yield a 2  2
implicit table; the natural logarithm is taken of each cell
5. “[C1:D2] is a 2  2 range; the number 3 is added to the values in the table for this
range, forming a 2  2 implicit table; the floor function is used to find the nearest
integer less than, for each cell.
6. the elements of the two implicit tables are compared element-by-element, with TRUE
given if the element of the first is strictly less than than the element of the second.

Find Expression
The find_expression is a conditional table cell specification in which the set of cells to con-
sider is part of the boolean expression. The syntax for this expression is:
left_spec “operator” right_spec
where “operator” is a standard EViews comparison operator such as “>”, “<>” “<=”,
“=”, etc., and where the left_spec and right_spec consist of one of:
• a literal value, e.g., the number 37, or the string “Kansas” or “New Mexico”.
• a cell range, enclosed in “[]”, e.g. “[A1:C9]”, “[R1C1:R10C30]”.

Most of the discussion in “Boolean Expression” on page 69 applies here, with the only dif-
ference being that the target range will be the larger of the left_spec and right_spec ranges.

For example,
string s = tab1.@find("[b1:c15]>0.3")

returns a list of cells between B1 and C15 greater than 0.3,


string s = tab1.@find("[@all]=0.5")

returns a list of cells in the table equal to 0.5,


string s = t.@find("[b3:c5]<[d5]")

returns a list of cells between B3 and C5 less than cell D5.

Note that since the find_expression must be enclosed in double-quotes inside the @find
function, the use of string literals will require “""” escape sequences to include the actual
quotes in the comparison.
string s = tabl1.@find("[a1:e67]= ""1949q4""")

returns a list of cells between A1 and E67 matching the string “1949q4” (string comparisons
in find ignore case);
string s = t.@find("@instr([@all],""in"")")
Exporting Tables to Files—73

returns a list of cells in the table containing the substring “in”;

Labeling Tables
Tables have a label view to display and edit information such as the graph name, last modi-
fied date, and remarks. To modify or view the label information, use the Table::label
command:
table11.label(r) Results from GMM estimation

This command shows the label view, and the “r” option appends the text “Results from
GMM estimation” to the remarks field of TABLE11.

To return to the basic table view, use the table keyword:


table11.table

All changes made in label view will be saved with the table.

Printing Tables
To print a table, use the print (p. 566) command, followed by the table object name. For
example:
print table11

The print destination is taken from the EViews global print settings.

Exporting Tables to Files


You may use the table Table::save procedure to save the table to disk as an Excel 2007
XLSX, CSV, tab-delimited ASCII text, RTF, HTML, Enhanced Metafile, LaTeX, PDF, or Mark-
down file.

You must specify a file name and an optional file type, and may also provide options to spec-
ify the cells to be saved, text to be written for NA values, and precision with which numbers
should be written. RTF and HTML files also allow you to save the table in a different size
than the current display. If a file type is not provided, EViews will write a CSV file.

For example:
tab1.save(t=csv, n="NAN") mytable

saves TAB1 in the default directory as a CSV file “Mytable.CSV”, with NA values translated
to the text “NAN”.

Alternately, the command:


tab1.save(r=B2:C10, t=html, s=.5) c:\data\MyTab2
74—Chapter 3.Customizing Spreadsheet Views

saves the specified cells in TAB1 as an HTML file to “Mytab2.HTM” in the directory
“c:\data”. The table is saved at half of the display size.

Customizing Spreadsheet Views


Several of the table procs for customizing table display may also be used for customizing
spreadsheet views of objects. You may use Series::setformat, Series::setindent,
Series::setjust, and Series::setwidth to modify the spreadsheet view of a series.
Similar procs are available for other objects with table views (e.g., alpha, group, and matrix
objects).

Suppose, for example, that you wish to set the format of the spreadsheet view for series
SER1. Then the commands:
ser1.setformat f.5
ser1.setjust right center
ser1.setindent 3
ser1.setwidth 10
ser1.sheet

sets the spreadsheet display format for SER1 and then displays the view.

Similarly, you may set the characteristics for a matrix object using the commands:
mat1.setformat f.6
mat1.setwidth 8
mat1.sheet

For group spreadsheet formatting, you must specify a column range specification. For exam-
ple:
group1.setformat(2) (f.7)
group1.setwidth(2) 10
group1.setindent(b) 6
group1.sheet

set the formats for the second series in the group, then displays the spreadsheet view.
group1.setwidth(@all) 10

sets the width for all columns in the group spreadsheet to 10.

Note that the group specified formats are used only to display series in the group and are not
exported to the underlying series. Thus, if MYSER is the second series in GROUP1, the
spreadsheet view of MYSER will use the original series settings, not those specified using the
group procs.
Table Summary—75

Table Summary
See “Table,” on page 1072 of the Object Reference for a full listing of formatting procs that
may be used with table objects.
76—Chapter 3.Table Summary
Chapter 4. Working with Spools

The EViews spool object allows you to create sets of output comprised of tables, graphs,
text, and other spool objects. Spools allow you to organize EViews results, allowing you to
generate a log of output for a project, or perhaps to collect output for a presentation.

The following discussion focuses on command methods for working with a spool object. A
general description of the spool object, featuring a discussion of interactive approaches to
working with your spool, may be found in Chapter 18. “Spool Objects,” on page 953 of
User’s Guide I.

Creating a Spool
There are two methods you may use to create a spool. You may declare a spool using the
spool command, or you may print an object to a new spool.

To declare an empty spool, use the keyword spool followed by a name for the new spool:
spool myNewSpool

creates a new, empty spool object MYNEWSPOOL.

A new spool may also be created by printing from an object to a non-existent spool. To print
to a spool you must redirect the output of print jobs to the spool using the output com-
mand. For example, the command:
output(s) myNewSpool

instructs EViews to send all subsequent print jobs to the MYNEWSPOOL spool (see output
(p. 533)).

Once you redirect your output, you may create a spool using the print command or the “p”
option of an object view or procedure.
tab1.print

creates the spool object MYNEWSPOOL and appends a copy of TAB1. Alternately,
eq1.output(p)

appends the EQ1 equation output to the newly created spool object.

To turn off redirection, simply issue the command


output off
78—Chapter 4.Working with a Spool

Working with a Spool


Spool objects provide easy-to-use tools for working with the objects in the spool. Among
other things, you may manage (add, delete, extract, rearrange, hide) or customize (resize,
space and indent, title and comment, and edit) the spool and the individual objects in a
spool.

Adding Objects
You may add objects to a spool by printing to the spool, or by using the Spool::append
and Spool::insert procs.

Printing to a Spool
Earlier, we saw how one may redirect subsequent print jobs to the spool object using the
output (p. 533) command to change the default print destination. Once redirection is in
place, simply use the print command or the “p” option to send view or procedure output
to the spool. The following command lines:
output(s) myOldSpool
ser01.line(p)
grp01.scat(p)
eq1.wald(p) c(1)=c(2)

redirect output to the existing spool object MYOLDSPOOL, then adds a line graph of SER01,
a scatterplot of the series in GRP01, and the table output of a Wald test for equation EQ1 to
the spool, in that order.

Note that the three output objects in the spool will be named UNTITLED01, UNTITLED02,
and UNTITLD03.

To turn off redirection, simply issue the command:


output off

Appending and Inserting


You may use the Spool::append procedure to add output objects to the end of an existing
spool object. You may insert any valid EViews object view into a spool. For example,
spool01.append ser01.line

appends a line graph of SER01 to the end of SPOOL01.

The name of the object in the spool will be the next available name beginning with “UNTI-
TLED”. For example, if two objects have already been appended to SPOOL01, named UNTI-
TLED01 and UNTITLED02, then the line graph of SER01 will be named UNTITLED03.

You may append multiple EViews objects using a single append command:
Working with a Spool—79

spool03.append ser02.line ser03

appends a line graph of SER02 and the default spreadsheet view of SER03 to the end of
SPOOL03.

The Spool::insert proc offers additional control over the location of the added object by
allowing you to specifying an integer position for the inserted object. If a position is not
specified or the specified position is greater than the number of objects already in the spool,
the object will be appended to the end. The command:
spool01.insert(loc=3) series01

inserts the default spreadsheet view of SERIES01 into SPOOL01 at position three. All existing
objects in the spool from position three and higher are pushed down in the list to accommo-
date the new object.

You may include more than one object view using a single insert command:
spool01.insert(loc=5) "eq1.wald c(1)=c(2)" series01.uroot

inserts both the results for a Wald test on EQ1, and the results for a unit root test for
SERIES01 into the spool in the fifth and sixth positions. Existing objects from the fifth posi-
tion onward will be moved down to the seventh position so that they follow the unit root
table. Note that since the Wald test command contains spaces, we require the use of double
quotes to delimit the expression.

Alternately, insert accepts an object name for the location and an optional offset keyword.
The command:
spool01.insert(loc=obj3) mycity.line

adds the line graph view of MYCITY to SPOOL01, placing it before OBJ3. You may modify
the default positioning by adding the “offset=after” option,
spool01.insert(loc=obj3, offset=after) mycity.line

so that the line graph is inserted after OBJ3.

You may use insert or append to add spool objects to a spool. Suppose that we have the
spool objects SPOOL01 and STATESPOOL. Then
spool01.insert statespool

adds STATESPOOL to the end of SPOOL01.

Subsequent insert commands may be used to place objects before, after, or inside of the
spool object. The commands
spool01.insert(loc=state) mycity.line
spool01.insert(loc=state, offset=after) mytown.hist
80—Chapter 4.Working with a Spool

inserts a line graph view of MYCITY before, and the histogram view of MYTOWN after the
STATE spool. You may also use the “offset=” option to instruct EViews to place the new
output object inside of an embedded spool:
spool01.insert(loc=state, offset=first) mycity.boxplot
spool01.insert(loc=state, offset=last) mystate.stats

places a boxplot view of MYCITY and a descriptive statistics view of MYSTATE inside of the
STATE spool object. The boxplot view is inserted at the beginning of STATE, while the
descriptive statistics view is appended to the end of STATE.

Objects within a embedded spool should be referred to using the full path description. For
example, suppose we have a spool object COUNTY which we wish to add to the end of the
previously embedded spool STATE. Then,
spool01.insert(loc=state, offset=last) county

inserts COUNTY as the last member of the spool STATE, and:


spool01.insert(loc=state/county, offset=first) mycity.bar

inserts a bar graph of MYCITY into the first position of the COUNTY spool.

Naming Objects
The default name of an object when it is inserted into a spool is UNTITLED followed by the
next available number (e.g. UNTITLED03). When using the Spool::append or the
Spool::insert procs may use the “name=” option to specify a name.

Alternately, you may use the Spool::name command to change the name of an object in
the spool. For example,
spool01.name untitled03 losangeles

renames the UNTITLED03 object to LOSANGELES. Note that names are not case-sensitive,
and that they must follow EViews’ standard naming conventions for objects. Names must
also uniquely identify objects in the spool.

To rename an object contained in an embedded spool, you should provide the full path
description of the object. For example, the command:
spool01.name untitled01/untitled02 newyork

renames the object UNTITLED02 which is contained in the spool UNITITLED01 to


NEWYORK.

Object Displaynames
The Spool::displayname proc may also be used to alter the display name of an object.
The default display name of an object is simply the uppercase version of the object name.
Display names, which are case-sensitive, not restricted to be valid object names, and need
Working with a Spool—81

not be unique, allow you to provide a more descriptive label in the tree pane view when dis-
playing object names.

For example,
spool01.displayname untitled03 "Los Angeles"

sets the display name for UNTITLED03 object to the text “Los Angeles”. Note that since the
desired display name has spaces, we have enclosed the text in double-quotes.

Similarly,
spool01.displayname untitled01/untitled02 "New York"

sets the display name for UNTITLED02 in the spool UNITITLED01 to “New York”.

Object Comments
The Spool::displayname may be used to assign a comment to an object in the spool. Set-
ting a comment for an object is similar to setting the display name. Comments can be multi-
line; you may use “\n” to indicate the start of a new line in a comment.
Spool01.comment untitled01 "The state population of Alabama as
found\nfrom http://www.census.gov/popest/states/NST-ann-
est.html."

assigns the following comment to object UNTITLED01:


“The state population of Alabama as found
from http://www.census.gov/popest/states/NST-ann-est.html.”

Removing Objects
Use the Spool::remove proc to delete objects from a spool. Follow the remove keyword
with names of the objects to be deleted. The unique object name should be used; the display
name cannot be used as a valid argument for the remove command.
spool01.remove untitled02 untitled01 untitled03

removes the three objects UNTITLED01, UNTITLED02, UNTITLED03 from SPOOL01. Note
that the order at which objects are specified is unimportant.

Extracting Objects
Objects within a spool are not confined to spools forever; they may be extracted to other
spools using Spool::extract. An independent copy of the specified object will be made.
Note that only one object may be extracted at a time. For instance, referring to our example
above, where we have a STATE spool containing a COUNTY spool,
spool01.extract state/county

creates an untitled spool containing the objects in the COUNTY spool.


82—Chapter 4.Printing the Spool

Similarly:
spool01.extract(mycounty) state/county

Customizing the Spool


Titles and Comments
Each object in a spool has both an object name and a display name. By default, the object
name is shown. The object name is not case sensitive, while the display name can be multi-
ple words and is case sensitive.

Setting a comment for an object is similar to setting the display name. Comments can be
multiline; you may use “\n” to indicate the start of a new line in a comment.
Spool01.comment untitled01 "The state population of Alabama as
found\nfrom http://www.census.gov/popest/states/NST-ann-
est.html."

assigns the following comment to object UNTITLED01:


“The state population of Alabama as found
from http://www.census.gov/popest/states/NST-ann-est.html.”

Customizing the Appearance


General properties of a spool may be modified using the Spool::options proc. These
properties include the display of the object tree, borders, titles, comments, and the use of the
object name or display name. To change these settings, use the options keyword followed
by the characteristic you wish to change.

To turn off the tree and display titles, displaynames and comments for SPOOL01:
spool01.options -tree titles displaynames comments

creates a spool with the same objects and names it MYCOUNTY.

Printing the Spool


Printing a entire spool object is the same as printing any other object in EViews, simply use
the print (p. 566) command followed by the name of the spool:
print spool01

prints all of SPOOL01.

To print an object stored in SPOOL01, us the Spool::print proc and specify the name of
the object within the spool that you wish to print. For example,
spool01.print state/county
Spool Summary—83

prints the COUNTY object, which is located in the STATE spool in SPOOL01. The
Spool::print proc also allows you to print multiple objects in the spool.
spool01.print state county

prints both the STATE and COUNTY objects individually.

When printing from the command window, the Print Options dialog will be displayed for
each object specified, allowing you to modify printer settings. When printing from a pro-
gram, the current printer settings will be used. To modify the current printer settings, you
may use File/Print Setup to set the global print defaults (“Print Setup,” on page 2562 of
User’s Guide I).

Spool Summary
See “Spool,” on page 904 of the Object Reference for a full listing of procedures that may be
used with spool objects.
84—Chapter 4.Spool Summary
Chapter 5. Strings and Dates

Strings
An alphanumeric string is a set of characters containing alphabetic (“alpha”) and
numeric characters, and in some cases symbols, found on a standard keyboard. Strings
in EViews may include spaces and dashes, as well as single or double quote characters.
Note also that EViews does not support unicode characters.

Strings are used in EViews in a variety of places. “Using Strings in EViews” on


page 101 offers a brief overview.

When entering alphanumeric values into EViews, you generally should enclose your
characters in double quotes. The following are all examples of valid string input:
"John Q. Public"
"Ax$23!*jFg5"
"000-00-0000"
"(949)555-5555"
"11/27/2002"
"3.14159"

You should use the double quote character as an escape character for double quotes in
a string. Simply enter two double quote characters to include the single double quote
in the string:
"A double quote is given by entering two "" characters."

Bear in mind that strings are simply sequences of characters with no special interpreta-
tion. The string values “3.14159” and “11/27/2002” might, for example, be used to rep-
resent a number and a date, but as strings they have no such intrinsic interpretation.
To provide such an interpretation, you must use the EViews tools for translating string
values into numeric or date values (see “String Information Functions” on page 90 and
“Translating between Date Strings and Date Numbers” on page 110).

Lastly, we note that the empty, or null, string (“”) has multiple interpretations in
EViews. In settings where we employ strings as a building block for other strings, the
null string is interpreted as a blank string with no additional meaning. If, for example,
we concatenate two strings, one of which is empty, the resulting string will simply be
the non-empty string.

In other settings, the null string is interpreted as a missing value. In settings where we
use string values as a category, for example when performing categorizations, the null
string is interpreted as both a blank string and a missing value. You may then choose
86—Chapter 5.Strings

to exclude or not exclude the missing value as a category when computing a tabulation
using the string values. This designation of the null string as a missing value is recognized
by a variety of views and procedures in EViews and may prove useful.

Likewise, when performing string comparisons using blank strings, EViews generally treats
the blank string as a missing value. As with numeric comparisons involving missing values,
comparisons involving missing values will often generate a missing value. We discuss this
behavior in greater detail in our discussion of “String Comparison (with empty strings)” on
page 88.

String Operators
The following operators are supported for strings: (1) concatenation—plus (“+”), and (2)
relational—equal to (“=”), not equal to (“<>”), greater than (“>”), greater than or equal
to (“>=”), less than (“<“), less than or equal to (“<=”).

String Concatenation Operator


Given two strings, concatenation creates a new string which contains the first string fol-
lowed immediately by the second string. You may concatenate strings in EViews using the
concatenation operator, “+”. For example,
"John " + "Q." + " Public"
"3.14" + "159"

returns the strings


"John Q. Public"
"3.14159"

Bear in mind that string concatenation is a simple operation that does not involve interpreta-
tion of strings as numbers or dates. Note in particular that the latter entry yields the concat-
enated string, “3.14159”, not the sum of the two numeric values, “162.14”. To obtain
numeric results, you will first have to convert your strings into a number (see “String Infor-
mation Functions” on page 90).

Lastly, we note that when concatenating strings, the empty string is interpreted as a blank
string, not as a missing value. Thus, the expression
"Mary " + "" + "Smith"

yields
"Mary Smith"

since the middle string is interpreted as a blank.


Strings—87

String Relational Operators


The relational operators return a 1 if the comparison is true, and 0 if the comparison is false.
In some cases, relational comparisons involving null strings will return a NA.

String Ordering
To determine the ordering of strings, EViews employs the region-specific collation order as
supplied by the Windows operating system using the user’s regional settings. Central to the
tasks of sorting or alphabetizing, the collation order is the culturally influenced order of
characters in a particular language.

While we cannot possibly describe all of the region-specific collation order rules, we note a
few basic concepts. First, all punctuation marks and other non alphanumeric characters,
except for the hyphen and the apostrophe precede the alphanumeric symbols. The apostro-
phe and hyphen characters are treated distinctly, so that “were” and “we’re” remain close in
a sorted list. Second, the collation order is case specific, so that the character “a” precedes
“A”. In addition, similar characters are kept close so that strings beginning with “a” are fol-
lowed by strings beginning with “A”, ahead of strings beginning with “b” and “B”.

Typically, we determine the order of two strings by evaluating strings character-by-character,


comparing pairs of corresponding characters in turn, until we find the first pair for which
the strings differ. If, using the collation order, we determine the first character precedes the
second character, we say that the first string is less than the second string and the second
string is greater than the first. Two strings are said to be equal if they have the same number
of identical characters.

If the two strings are identical in every character, but one of them is shorter than the other,
then a comparison will indicate that the longer string is greater. A corollary of this statement
is that the null string is less than or equal to all other strings.

The multi-character elements that arise in many languages are treated as single characters
for purposes of comparison, and ordered using region-specific rules. For example, the “CH”
and “LL” in Traditional Spanish are treated as unique characters that come between “C” and
“L” and “M”, respectively.

String Comparison (with non-empty strings)


Having defined the notion of string ordering, we may readily describe the behavior of the
relational operators for non-empty (non-missing) strings. The “=” (equal), “>=” (greater
than or equal), and “<=” (less than or equal), “<>” (not equal), “>” (greater than), and
“<” (less than) comparison operators return a 1 or a 0, depending on the result of the string
comparison. To illustrate, the following (non region-specific) comparisons return the value
1,
"abc" = "abc"
"abc" <> "def"
88—Chapter 5.Strings

"abc" <= "def"


"abc" < "abcdefg"
"ABc" > "ABC"
"abc def" > "abc 1ef"

while the following return a 0,


"AbC" = "abc"
"abc" <> "abc"
"aBc" >= "aB1"
"aBC" <= "a123"
"abc" >= "abcdefg"

To compare portions of strings, you may use the functions @left, @right, and @mid to
extract the relevant part of the string (see “String Manipulation Functions” on page 92). The
relational comparisons,
@left("abcdef", 3) = "abc"
@right("abcdef", 3) = "def"
@mid("abcdef", 2, 2) = "bc"

all return 1.

In normal settings, EViews will employ case-sensitive comparisons (see “Case-Sensitive


String Comparison” on page 190 for settings that enable caseless element comparisons in
programs). To perform a caseless comparison, you should convert the expressions to all
uppercase, or all lowercase using the @upper, or @lower functions. The comparisons,
@upper("abc") = @upper("aBC")
@lower("ABC" = @lower("aBc")

both return 1.

To ignore leading and trailing spaces, you should use the @ltrim, @rtrim, and @trim func-
tions remove the spaces prior to using the operator. The relational comparisons,
@ltrim(" abc") = "abc"
@ltrim(" abc") = @rtrim("abc ")
@trim(" abc ") = "abc"

all return 1.

String Comparison (with empty strings)


Generally speaking, the relational operators treat the empty string as a missing value and
return the numeric missing value NA when applied to such a string. Suppose, for example
that an observation in the alpha series X contains the string “Apple”, and the corresponding
observation in the alpha series Y contains a blank string. All comparisons (“X=Y”, “X>Y”,
Strings—89

“X>=Y”, “X<Y”, “X<=Y”, and “X<>Y”) will generate an NA for that observation since
the Y value is treated as a missing value.

Note that this behavior differs from EViews 4 and earlier in which empty strings were
treated as ordinary blank strings and not as a missing value. In these versions of EViews, the
comparison operators always returned a 0 or a 1. The change in behavior, while regrettable,
was necessary to support the use of string missing values.

It is still possible to perform comparisons using the previous behavior. One approach is to
use the special functions @eqna and @neqna for equality and strict inequality comparisons
without propagating NAs (see “String Information Functions” on page 90). For example, you
may use the expressions
@eqna(x, y)
@neqna(x, y)

so that blanks in string X or Y are treated as ordinary string values. Using these two func-
tions, the observation where X contains “Apple” and Y contains the “” will evaluate to 0 and
1, respectively instead of NA.

Similarly, if you specify a relational expression involving a literal blank string, EViews will
perform the test treating empty strings as ordinary string values. If, for example, you test
x = ""

or
x < ""

all of the string values in X will be tested against the string literal “”. You should contrast this
behavior with the behavior for the non-literal tests “X=Y” and “X<Y” where blank values
of X or Y result in an NA comparison.

Lastly, EViews provides a function for the strict purpose of testing whether a string value is
an empty string. The @isempty function tests whether a string is empty. The relational
equality test against the blank string literal “” is equivalent to this function.

String Lists
A string list is an ordinary string that is interpreted as a space delimited list of string ele-
ments. For example, the string
"Here I stand"

may be interpreted as containing three elements, the words “Here”, “I” and “stand”. Double
quotes may be used to include multiword elements in a list. Bearing in mind that the quote
is used as an escape character for including quotes in strings, the list
"""Chicken Marsala"" ""Beef Stew"" Hamburger"
90—Chapter 5.Strings

contains three elements, the expressions “Chicken Marsala”, “Beef Stew”, and “Hamburger”.
Notice how the escaped double quotes are used to group words into single list elements.

Interpreting a string as a list of elements allows us to make use of functions which operate
on each element in the string, rather than on each character. These methods can be useful
for string manipulation and pattern searching. For example, we may find the intersection,
union, or cross of two string lists. Additionally, we may manipulate the elements of a string
list and find the elements that match or do not match a given pattern. For example, the
string list function
@wkeep("ABC ABCC AABC", "?B*")

uses the pattern “?B*” to filter the string list “ABC ABCC AABC”. Elements with a single
character, followed by the character “B”, then followed by any number of other characters
are kept, returning: “ABC ABCC”.

String Functions
EViews provides a number of functions that may either be used with strings, or return string
values. Below, we provide a brief summary of the more commonly employed functions.

Functions that treat a string as a string list begin with a “w”. Some string functions have cor-
responding list functions with the same name, preceded by a “w”. For instance, @left
returns the leftmost characters of a string, while @wleft returns the leftmost elements of a
string list.

“String Function Summary” on page 331 offers more extensive list of string functions and
pointers to documentation with additional detail.

String Information Functions


The following is a brief summary of commonly used functions that take a string argument
and return a number.
• @length(str): returns an integer value for the length of the string str.
@length("I did not do it")
returns the value 15.
A shortened keyword form of this function, @len, is also supported.
See @length (p. 944).
• @wcount(str_list): returns an integer value for the number of elements in the string
list str_list.
@wcount("I did not do it")
returns the value 5.
See @wcount (p. 1188).
Strings—91

• @instr(str1, str2[, int]): finds the starting position of the target string str2 in the base
string str1. By default, the function returns the location of the first occurrence of str2
in str1. You may provide an optional integer int to specify the occurrence. If the
requested occurrence of the target string is not found, @instr will return a 0.
The returned integer is often used in conjunction with @mid to extract a portion of the
original string.
@instr("1.23415", "34")
returns the value 4, since the substring “34” appears beginning in the fourth character
of the base string, so
@mid("1.23415", @instr("1.23415", "34"))
returns “3415”.
See @instr (p. 924).
• @wfind(str_list, str_cmp): looks for the string str_cmp in the string list str_list, and
returns the element position in the list or 0 if the string is not in the list.
@wfind("I did it", "did")
returns the value 2.
The @wfindnc function performs the same operation, but the comparison is not case-
sensitive.
See @wfind (p. 1196) and @wfindnc (p. 1197).
• @isempty(str): tests for whether str is a blank string, returning a 1 if str is a null
string, and 0 otherwise.
@isempty("1.23415")
returns a 0, while
@isempty("")
returns the value 1.
See @isempty (p. 926).
• @eqna(str1, str2): tests for equality of str1 and str2, treating null strings as ordinary
blank strings, and not as missing values. Strings which test as equal return a 1, and 0
otherwise. For example,
@eqna("abc", "abc")
returns a 1, while
@eqna("", "def")
returns a 0.
See @eqna (p. 873).
92—Chapter 5.Strings

• @neqna(str1, str2): tests for inequality of str1 and str2, treating null strings as ordi-
nary blank strings, and not as missing values. Strings which test as not equal return a
1, and 0 otherwise.
@neqna("abc", "abc")
returns a 0,
@neqna("", "def")
returns a 1.
See @neqna (p. 1010).
• @val(str[, fmt]): converts the string representation of a number, str, into a numeric
value. If the string has any non-digit characters, the returned value is an NA. You may
provide an optional numeric format string fmt. See “String Conversion Functions” on
page 97.
See @val (p. 1175).
• @dateval(str[, fmt]): converts the string representation of a date string, str, into a
date number using the optional format string fmt. See “String Conversion Functions”
on page 97.
See @dateval (p. 825).
• @dtoo(str): (Date TO Obs) converts the string representation of a date, str, into an
observation value for the active workfile. Returns the scalar offset from the beginning
of the workfile associated with the observation given by the date string. The string
must be a valid EViews date.
create d 2/1/90 12/31/95
%date = "1/1/93"
!t = @dtoo(%date)
returns the value !T=762.
Note that @dtoo will generate an error if used in a panel structured workfile.
See @dtoo (p. 847).

String Manipulation Functions


The following is a brief summary of some commonly used functions that take strings as an
argument and return a string.
• @left(str, int): returns a string containing the int characters at the left end of the
string str. If there are fewer than int characters, @left will return the entire string.
@left("I did not do it", 5)
returns the string “I did”.
Strings—93

See @left (p. 942).


• @wleft(str_list, int): returns a string containing the int elements at the left end of the
string list str_list. If there are fewer than int elements, @wleft will return the entire
string list.
@wleft("I did not do it", 3)
returns the string “I did not”.
See @wleft (p. 1203).
• @right(str, int): returns a string containing the int characters at the right end of a
string. If there are fewer than int characters, @right will return the entire string.
@right("I doubt that I did it", 8)
returns the string “I did it”.
See @right (p. 1075).
• @wright(str_list, int): returns a string containing the int elements at the right end of
a string list. If there are fewer than int elements, @wright will return the entire string.
@wright("I doubt that I did it", 3)
returns the string “I did it”.
See @wright (p. 1214).
• @mid(str, int1[, int2]): returns the string consisting of the characters starting from
position int1 in the string. By default, @mid returns the remainder of the string, but
you may specify the optional integer int2, indicating the number of characters to be
returned.
@mid("I doubt that I did it", 9, 10)
returns “that I did”.
@mid("I doubt that I did it", 9)
returns the string “that I did it”.
See @mid (p. 974).
• @wmid(str_list, int1[, int2]): returns the string consisting of the elements starting from
position int1 in the string. By default, @wmid returns all remaining elements of the
string, but you may specify the optional integer int2, indicating the number of ele-
ments to be returned.
@wmid("I doubt that I did it", 2, 3)
returns “doubt you did”.
@wmid("I doubt that I did it", 4)
returns the string “I did it”.
94—Chapter 5.Strings

See @wmid (p. 1206).


• @word(str_list, int): returns the int element of the string list.
@word("I doubt that I did it", 2)
returns the second element of the string, “doubt”.
See @word (p. 1208).
• @wordq(str_list, int): returns the int element of the string list, while preserving
quotes.
@wordq("""Chicken Marsala"" ""Beef Stew""", 2)
returns the second element of the string, “Beef Stew”. The @word function would
return the same elements, but would not include quotation marks in the string.
See @wordq (p. 1209).
• @insert(str1, str2, int): inserts the string str2 into the base string str1 at the position
given by the integer int.
@insert("I believe it can be done", "not ", 16)
returns “I believe it cannot be done”.
See @insert (p. 923).
• @wkeep(str_list, "pattern_list"): returns the list of elements in str_list that match the
string pattern pattern_list. The pattern_list is space delimited, and may be made up of
any number of “?” (indicates any single character) or “*” (indicates any number of
characters).
@wkeep("ABC DEF GHI JKL", "?B? D?? *I")
keeps the first three elements of the string list, returning the string “ABC DEF GHI”.
See @wkeep (p. 1202).
• @wdrop(str_list, "pattern_list"): returns a string list, dropping elements in str_list that
match the string pattern pattern_list. The pattern_list is space delimited, and may be
made up of any number of “?” (indicates any single character) or “*” (indicates any
number of characters).
@wdrop("ABC DEF GHI JKL", "?B? D?? *I")
drops the first three elements of the string list, returning the string “JKL”.
See @wdrop (p. 1191).
• @replace(str1, str2, str3[, int]): returns the base string str1, with the replacement
str3 substituted for the target string str2. By default, all occurrences of str2 will be
replaced, but you may provide an optional integer int to specify the number of occur-
rences to be replaced.
@replace("Do you think that you can do it?", "you", "I")
Strings—95

returns the string “Do I think that I can do it?”, while


@replace("Do you think that you can do it?", "you", "I", 1)
returns “Do I think that you can do it?”.
See @replace (p. 1070).
• @wreplace(str_list, “src_pattern”, “replace_pattern”): returns the base string list
str_list, with the replacement pattern replace_pattern substituted for the target pattern
src_pattern. The pattern lists may be made up of any number of “?” (indicates any sin-
gle character) or “*” (indicates any number of characters).
@wreplace("ABC AB", "*B*", "*X*")
replaces all instances of “B” with “X”, returning the string “AXC AX”.
@wreplace("ABC DDBC", "??B?", "??X?")
replaces all instances of “B” which have two leading characters and one following
character, returning the string “ABC DDXC”.
See @wreplace (p. 1211).
• @ltrim(str): returns the string str with spaces trimmed from the left.
@ltrim(" I doubt that I did it. ")
returns “I doubt that I did it. ”. Note that the spaces on the right remain.
See @ltrim (p. 953).
• @rtrim(str): returns the string str with spaces trimmed from the right.
@rtrim(" I doubt that I did it. ")
returns the string “ I doubt that I did it.”. Note that the spaces on the left remain.
See @rtrim (p. 1100).
• @trim(str): returns the string str with spaces trimmed from the both the left and the
right.
@trim(" I doubt that I did it. ")
returns the string “I doubt that I did it.”
See @trim (p. 1153).
• @upper(str): returns the upper case representation of the string str.
@upper("I did not do it")
returns the string “I DID NOT DO IT”.
See @upper (p. 1171).
• @lower(str): returns the lower case representation of the string str.
@lower("I did not do it")
96—Chapter 5.Strings

returns the string “i did not do it”.


See @lower (p. 951).
• @addquotes(str): returns the string str with quotation marks added to the left and
right. Given a string S1 that contains the unquoted text: I did not do it,
@addquotes(S1)
returns the quoted string “I did not do it”.
See @addquotes (p. 715).
• @stripquotes(str): returns the string str with quotation marks removed from the left
and right. Given a string S1 that contains the text: “I did not do it”,
@stripquotes(S1)
returns the unquoted string: “I did not do it”.
See @stripquotes (p. 1131).
• @stripparens(str): returns the string str with parentheses removed from the left and
right. Given a string S1 that contains the text: “(I did not do it)”,
@stripparens(S1)
returns the string: “I did not do it”.
See @stripparens (p. 1130).
• @wintersect(str_list1, str_list2): returns the intersection of str_list1 and str_list2.
@wintersect("John and Greg won", "Mark won but Greg lost")
returns the string “won Greg”.
See @wintersect (p. 1201).
• @wunion(str_list1, str_list2): returns the union of str_list1 and str_list2.
@wunion("ABC DEF", "ABC G H def")
returns the string “ABC DEF G H def”. Each new element is added to the string list,
skipping elements that have already been added to the list.
See @wunion (p. 1216).
• @wunique(str_list): returns str_list with duplicate elements removed from the list.
@wunique("fr1 fr2 fr1")
returns the string “fr1 fr2”.
See @wunique (p. 1217).
• @wnotin(str_list1, str_list2): returns elements of str_list1 that are not in str_list2.
@wnotin("John and Greg won", "and Greg")
returns the string “John won”.
Strings—97

See @wnotin (p. 1207).


• @wcross(str_list1, str_list2[, “pattern”]): returns str_list1 crossed with str_list2,
according to the string pattern. The default pattern is “??”, which indicates that each
element of str_list1 should be crossed individually with each element of str_list2.
@wcross("ABC DEF", "1 2 3", "?-?")
returns the string list “ABC-1 ABC-2 ABC-3 DEF-1 DEF-2 DEF-3”, inserting a dash (“-”)
between each crossed element as the “?-?” pattern indicates.
See @wcross (p. 1188).
• @winterleave(str_list1, str_list2[, count1, count2]): Interleaves str_list1 with
str_list2, according to the pattern specified by count1 and count2. The default uses
counts of one.
@winterleave("A B C", "1 2 3")
interleaves “A B C” with “1 2 3” to produce the string list “A 1 B 2 C 3”.
See @winterleave (p. 1200).
• @wsort(str_list[,”D”]): Returns sorted elements of str_list. Use the “D” flag to sort in
descending order.
@wsort("fq8 Fq8 xpr1", "D")
sorts the string in descending order: “xpr1 Fq8 fq8”.
See @wsort (p. 1215).
• @wdelim(str_list, "src_delim", "dest_delim"): returns a string list, replacing every
appearance of the src_delim delimiter in str_list with a dest_delim delimiter. Delimit-
ers must be single characters.
@wdelim("Arizona, California, Washington", ",", "-")
identifies the comma as the source delimiter and replaces each comma with a dash,
returning the string “Arizona-California-Washington”.
See @wdelim (p. 1189).

String Conversion Functions


The following functions convert between numbers or date numbers and strings:
• @datestr(date1[, fmt]): converts the date number date1 to a string representation
using the optional date format string, fmt.
@datestr(730088, "mm/dd/yy")
will return “12/1/99”,
@datestr(730088, "DD/mm/yyyy")
will return “01/12/1999”, and
98—Chapter 5.Strings

@datestr(730088, "Month dd, yyyy")


will return “December 1, 1999”, and
@datestr(730088, "w")
will produce the string “3”, representing the weekday number for December 1, 1999.
See “Dates” on page 104 for additional details on date numbers and date format
strings.
See @datestr (p. 824).
• @dateval(str[, fmt]): converts the string representation of a date string, str, into a
date number using the optional format string fmt.
@dateval("12/1/1999", "mm/dd/yyyy")
will return the date number for December 1, 1999 (730088) while
@dateval("12/1/1999", "dd/mm/yyyy")
will return the date number for January 12, 1999 (729765). See “Dates,” beginning on
page 104 for discussion of date numbers and format strings.
See @dateval (p. 825)
• @str(num[, fmt]): returns a string representation of the number num. You may pro-
vide an optional numeric format string fmt.
@str(153.4)
returns the string “153.4”.
To create a string containing 4 significant digits and leading “$” character, use
@str(-15.4435, "g$.4")
The resulting string is “-$15.44”.
The expression
@str(-15.4435, "f7..2")
converts the numerical value, -15.4435, into a fixed 7 character wide decimal string
with 2 digits after the decimal and comma as decimal point. The resulting string is
“ -15,44”. Note that there is a leading space in front of the “-” character making the
string 7 characters long.
The expression
@str(-15.4435, "e(..2)")
converts the numerical value, -15.4435, into a string written in scientific notation with
two digits to the right of the decimal point. The decimal point in the value will be rep-
resented using a comma and negative numbers will be enclosed in parenthesis. The
resulting string is “(1,54e+01)”. A positive value will not have the parenthesis.
@str(15.4435, "p+.1")
Strings—99

converts the numeric value, 15.4435, into a percentage where the value is multiplied
by 100. Only 1 digit will be included after the decimal and an explicit “+” will always
be included for positive numbers. The resulting value after rounding is “+1544.4”.
See @str (p. 1123).
• @val(str[, fmt]): converts the string representation of a number, str, into a numeric
value. If the string has any non-digit characters, the returned value is an NA. You may
provide an optional numeric format string fmt.
@val("1.23415")
See @val (p. 1175).

String Vector Functions


The following functions either take a string vector as an argument, or return a string vector:
@rows(str_vector): returns the number of rows in str_vector.
For a string vector SV01 with 10 rows,
@rows(sv01)
returns the integer 10.
• @wsplit(str_list): returns a string vector containing the elements of str_list.
If the string list SS01 contains “A B C D E F”, then
@wsplit(ss01)
returns an untitled svector, placing an element of SS01 in each row. Row one of the
svector contains “A”, row two contains “B”, etc.
See @wsplit (p. 1216).
• @wjoin(svector): returns a space delimited list containing the elements of svector.
This function is the inverse of the @wsplit function.
See @wjoin (p. 1202).

Special Functions that Return Strings


EViews provides a special, workfile-based function that uses the structure of the active
workfile page and returns a set of string values representing the date identifiers associated
with the observations.
• @strdate(fmt): returns the set of workfile row dates as strings in an Alpha series,
formatted using the date format string fmt. See “Special Date Functions” on page 122
for details.
See @strdate (p. 1128).
100—Chapter 5.Strings

In addition, EViews provides two special functions that return a string representations of the
date associated with a specific observation in the workfile, or with the current time.
• @otod(int): (Obs TO Date): returns a string representation of the date associated with
a single observation (counting from the start of the workfile). Suppose, for example,
that we have a quarterly workfile ranging from 1950Q1 to 1990Q4. Then
@otod(16)
returns the date associated with the 16th observation in the workfile in string form,
“1953Q4”.
See @otod (p. 1019).
• @otods(int): (Obs TO Date in Sample): returns a string representation of the date
associated with a single observation (counting from the start of the sample). Thus
@otods(2)
will return the date associated with the second observation in the current sample.
Note that if int is negative, or is greater than the number of observations in the cur-
rent sample, an empty string will be returned.
See @otods (p. 1020).
• @strnow(fmt): returns a string representation of the current date number (at the
moment the function is evaluated) using the date format string, fmt.
@strnow("DD/mm/yyyy")
returns the date associated with the current time in string form with 2-digit days,
months, and 4-digit years separated by a slash, “24/12/2003”.
See @strnow (p. 1132).

You may also ask EViews to report information about objects in the current workfile or data-
base, or a directory on your computer, in a form suitable for list processing:
• @wlookup(“pattern_list”[, “object_type_list”]): Returns a string list of all objects in the
workfile or database that satisfy the pattern_list and, optionally, the object_type_list.
The pattern_list may be made up of any number of “?” (indicates any single charac-
ter) or “*” (indicates any number of characters).
If a workfile contains a graph object named “GR01” and two series objects named
“SR1” and “SER2”, then
@wlookup("?R?","series")
returns the string “SR1”.
See @wlookup (p. 1204).
• @wdir(directory_str): returns a string list of all files in the directory directory_str. Note
that this does not include other directories nested within directory_str.
Strings—101

@wdir("C:\Documents and Settings")


returns a string list containing the names of all files in the “C:\Documents and Set-
tings” directory.
See @wdir (p. 1190).

Lastly, all EViews objects have data members which return information about themselves in
the form of a string. For example:
ser1.@updatetime

returns the last update time for the series SER1


eq1.@command

returns the full command line form of the estimation command.

For lists of the relevant data members see the individual object descriptions in Chapter 1.
“Object View and Procedure Reference,” on page 3.

Using Strings in EViews


Strings in EViews are primarily used in four distinct contexts: string variables, string objects,
string vectors, or Alpha series.

String Variables
A string variable is a temporary variable used in a program whose value is a string. String
variables, which only exist during the time that your EViews program is executing, have
names that begin with a “%” symbol. For example,
%value = "value in millions of u.s. dollars"
%armas = "ar(1) ar(2) ma(1) ma(2)"

are string variables declarations that may be used in program files.

See “String Variables,” on page 145 for extensive discussion of the role that these variables
play in programming.

String Objects
A string object is an EViews workfile object that holds a string of text:
string lunch = "Apple Tuna Cookie"
string dinner = """Chicken Marsala"" ""Beef Stew"" Hamburger"

creates the string objects LUNCH and DINNER, each containing the corresponding string lit-
eral. Note that we have used the double quote character as an escape character for double
quotes.
102—Chapter 5.Strings

Since a string object is an EViews workfile object, we may open and display its views. A
string object’s view may be switched between String and Word list views. The String view
for DINNER displays the text as a single string,
"Chicken Marsala" "Beef Stew" Hamburger

while the Word list view breaks up the text by element,


"Chicken Marsala"
"Beef Stew"
Hamburger

with each element on a separate line.

We emphasize the important distinction that string objects are named objects in the workfile
that may be saved with the workfile, while string variables are temporary variables that only
exist while an EViews program is running. Thus, string objects have the advantage that they
may be used interactively, while string variables may not be used outside of programs.
String objects can, however, go out of scope when the active workfile page changes, while
string variables are always in scope.

In all other respects, strings objects and string variables may be used interchangeably in pro-
grams. Either string object or string variables can be passed into subroutines for arguments
declared as type string.

String Vectors
An svector, or string vector, is an EViews object that holds a string in each row of the vector.
A string vector can be created by specifying the number of rows in the vector and providing
a name:
svector(3) svec

If a length is not specified, a one row svector will be created.

An svector can be populated by assigning a string or string literal to each row:


svec(1) = "gdp cost total"

fills the first row of SVEC with the string “gdp cost total”. To assign the same string to all
rows, omit the row number. The command
svec = "invalid"

will assign the string “invalid” to all rows of SVEC.

A multiple row svector may be populated using the @wsplit command, which creates a
string vector from a string list. For example,
svector svec
string st = "gdp cost total"
Strings—103

svec = @wsplit(st)

creates the string vector SVEC of default length one and a string object ST containing “gdp
cost total”. The @wsplit (p. 1216) command creates a three element svector from the ele-
ments of ST, placing the string “gdp” in the first row of the string vector, the string “cost” in
the second row, and the string “total” in the third row, and assigns it to SVEC, which is
resized accordingly.

Similarly, an svector will shrink if assigned to a smaller svector. For example,


svector svec3 = @wsplit("First Middle Last")
svector(10) svec10
svec10 = svec3

first creates the three row svector SVEC3, then assigns the strings “First”, “Middle”, and
“Last” to the first, second, and third rows, respectively. The third line creates a second ten
row svector, SVEC10. When SVEC3 is assigned to SVEC10, its values are copied over and
rows four through ten are removed from SVEC10.

An svector may also be filled by concatenating two strings or svectors. For instance,
svector s1 = @wsplit("A B C")
svector s2 = @wsplit("1 2 3")
svector ssvec = s1 + s2

creates two svectors S1 and S2, each with three rows. S1 contains the characters “A”, “B”,
and “C”, while S2 contains “1”, “2”, and “3”. The third command creates the svector SSVEC
and fills it with the concatenation of the other two svectors, producing “A1” on the first row,
“B2” on the second row, and “C3” on the third row.

More generally, any operation that can be performed on a string may be performed on ele-
ment of an svector. For example, given an svector whose first element contains the string
“Hello World” and whose second element contains “Hi there world”, the element assign-
ment statement
svector sv(3) = @left(sv(1),5) + " " + @mid(sv(2),4,5)

takes the left five characters of the first row (“Hello”), adds a space, concatenates five char-
acters from the second row, starting at the fourth character (“there”), and assigns it to the
third element of SV. Element three of SV now contains the string “Hello there”.

The row count of a string vector may be retrieved using the @rows command:
scalar sc = @rows(sv)

This is especially useful since svectors are dynamically resized when necessary.
104—Chapter 5.Dates

Alpha Series
EViews has a special series type for holding string data. An alpha series object contains a set
of observations on string values. Alpha series should be used when you wish to work with
variables that contain alphanumeric data, such as names, addresses, and other text.

Alpha series are distinguished from string vectors primarily in that their length is tied to the
length of the workfile.

See “Alpha Series,” on page 224 for discussion.

Dates
There are a variety of places in EViews where you may work with calendar dates. For most
purposes, users need not concern themselves with the intricacies of working with dates.
Simply enter your dates in familiar text notation and EViews will automatically interpret the
string for you.

Those of you who wish to perform more sophisticated operations with dates will, however,
need to understand some basic concepts.

In most settings, you may simply use text representations of dates, or date strings. For exam-
ple, an EViews sample can be set to include only observations falling between two dates
specified using date strings such as “May 11, 1997”, “1/10/1990” or “2001q1”. In these set-
tings, EViews understands that you are describing a date and will interpret the string accord-
ingly.

Date information may also be provided in the form of a date number. A date number is a
numeric value with special interpretation in EViews as a calendar date. EViews allows you
to convert date strings into date numbers which may be manipulated using a variety of
tools. These tools allow you to perform standard calendar operations such as finding the
number of days or weeks between two dates, the day of the week associated with a given
day, or the day and time 36 hours from now.

The remainder of this section summarizes the use of dates in EViews. (See Chapter 5.
“Strings and Dates,” on page 85 for reference material.) There are several tasks that are cen-
tral to working with dates:
• Translating between date strings and date numbers.
• Translating ordinary numbers into date numbers.
• Manipulating date numbers using operators and functions.
• Extracting information from date numbers.
Dates—105

Before turning to these tasks, we must first provide a bit of background on the characteris-
tics of date strings, date numbers, and a special class of strings called date formats, which
are sometimes employed when translating between the former.

Date Strings
Date strings are simply text representations of dates and/or times. Most of the conventional
ways of representing days, weeks, months, years, hours, minutes, etc., as text are valid date
strings.

To be a bit more concrete, the following are valid date strings in EViews:
"December 1, 2001"
"12/1/2001"
"Dec/01/01 12am"
"2001-12-01 00:00"
"2001qIV”

As you can see, EViews is able to handle a wide variety of representations of your dates and
times. You may use everything from years represented in 1, 2, and 4-digit Arabic form (“1”,
“01”, “99”, “1999”), to month names and abbreviations (“January”, “jan”, “Jan”), to quar-
ter designations in Roman numerals (“I” to “IV”), to weekday names and abbreviations
(“Monday”, “Mon”), to 12 or 24-hour representations of time (“11:12 pm”, “23:12”). A full
list of the recognized date string components is provided in “Date Formats” on page 106.

It is worth noting that date string representations may be divided up into those that are
unambiguous and those that are ambiguous. Unambiguous date strings have but a single
interpretation as a date, while ambiguous date strings may be interpreted in multiple ways.

For example, the following dates may reasonably be deemed unambiguous:


"March 3rd, 1950"
"1980Q3"
"9:52PM"

while the following dates are clearly ambiguous:


"2/3/4"
"1980:2"
"02:04"

The first date string in the latter set is ambiguous because we cannot tell which of the three
fields is the year, which is the month, and which is the day, since different countries of the
world employ different orderings. The second string is ambiguous since we cannot deter-
mine the period frequency within the year. The “2” in the string could, for example, refer to
the second quarter, month, or even semi-annual in the year. The final string is ambiguous
since it could be an example of a time of day in “hour:minute” format (2:04 am), or a date
106—Chapter 5.Dates

in “year:period” notation (i.e., the fourth month of the year 2002) or “period:year” notation
(i.e., the second month of 2004).

In settings where date input is required, EViews will generally accept date string values
without requiring you to provide formatting information. It is here that the importance of
the distinction between ambiguous and unambiguous date strings is seen. If the date string
is unambiguous, the free-format interpretation of the string as a date will produce identical
results in all settings. On the other hand, if the date string is ambiguous, EViews will use the
context in which the date is being used to determine the most likely interpretation of the
string. You may find that ambiguous date strings are neither interpreted consistently nor as
desired.

These issues, and methods of getting around the problem of ambiguity, are explored in
greater detail in “Translating between Date Strings and Date Numbers” on page 110.

Date Numbers
Date information is often held in EViews in the form of a date number. A date number is a
double precision number corresponding to an instance in time, with the integer portion rep-
resenting a specific day, and the decimal fraction representing time during the day.

The integer portion of a date number represents the number of days in the Gregorian prolep-
tic calendar since Monday, January 1, A.D. 0001 (a “proleptic” calendar is a calendar that is
applied to dates both before and after the calendar was historically adopted). The first repre-
sentable day, January 1, A.D. 1 has an integer value of 0, while the last representable day,
December 31, A.D. 9999, has an integer value of 3652058.

The fractional portion of the date number represents a fraction of the day, with resolution to
the millisecond. The fractional values range from 0 (12 midnight) up to (but not including) 1
(12 midnight). A value of 0.25, for example, corresponds to one-quarter of the day, or 6:00
a.m.

It is worth noting that the time of day in an EViews date number is accurate up to a particu-
lar millisecond within the day, although it can always be displayed at a lower “precision”
(larger unit of time). When date numbers are formatted to lower precisions, they are always
rounded down to the requested precision and never rounded up. Thus, when displaying the
week or month associated with a date number, EViews always rounds down to the begin-
ning of the week or month.

Date Formats
A date format string (or date format, for short) is a string made up of text expressions that
describe how components of a date and time may be encoded in a date string. Date formats
are used to provide an explicit description of a date string representation, and may be
employed when converting between strings or numbers and date numbers.
Dates—107

Before describing date formats in some detail, we consider a simple example. Suppose that
we wish to use the date string “5/11/1997” to represent the date May 11, 1997. The date for-
mat corresponding to this text representation is
"mm/dd/yyyy"

which indicates that we have, in order, the following components: a one or two-digit month
identifier, a “/” separator, a one or two-digit day identifier, a “/” separator, and a 4-digit year
identifier.

Alternatively, we might wish to use the string “1997-May-11” to represent the same date.
The date format for this string is
"yyyy-Month-dd"

since we have a four-digit year, followed by the full name of the month (with first letter cap-
italized), and the one or two-digit day identifier, all separated by dashes.

Similarly, the ISO 8601 representation for 10 seconds past 1:57 p.m. on this date is “1997-05-
11 13:57:10”. The corresponding format is
"yyyy-MM-DD HH:mi:ss"

Here, we have used the capitalized forms of “MM”, “DD”, and “HH” to ensure that we have
the required leading zeros.

A full description of the components of a date format is provided below. Some of the more
commonly used examples of date formats are listed in the options for the setformat object
commands (see, for example, Table::setformat (p. 1096) in the Object Reference).

Date Format Components


A date format may contain one or more of the following string fragments corresponding to
various date components. In most cases, there are various upper and lowercase forms of the
format component, corresponding either to the presence or absence of leading zeros, or to
the case of the string identifiers.

The following format strings are the basic components of a date format:

Years
Year formats use either two or four digit years, with or without leading zeros. The corre-
sponding date format strings are:
• “yyyy” or “YYYY”: four digit year without/with leading zeros.
• “yy” or “YY”: two digit year without/with leading zeros.
• “year” or “YEAR”: synonym for “yyyy” and “YYYY”, respectively.
108—Chapter 5.Dates

Semi-Annual
The semi-annual format corresponds to a single digit representing the period in the year:
• “s” or “S”: one digit half-year (1 or 2).

Quarters
Quarter formats allow for values entered in either standard (Arabic) or Roman numbers:
• “q” or “Q”: quarter number, always without leading zeros (1 to 4).
• “qr” or “QR”: quarter in Roman numerals following the case of the format string (“i”
to “iv” or “I” to “IV”.)

Months
Month formats may represent two-digit month values with or without leading zeros, three-
letter abbreviations for the month, or the full month name. The text identifiers may be all
lowercase, all uppercase or “namecase” in which we capitalize the first letter of the month
identifier. The corresponding format strings are given by:
• “mm” or “MM”: two-digit month without/with leading zeros.
• “mon”, “Mon”, or “MON”: three-letter form of month, following the case of the for-
mat string(“jan”, “Feb”, “MAR”).
• “month”, “Month”, or “MONTH”: full month name, following the case of the format
string (“january”, “February”, “MARCH”).

Weeks
Week of the year formats may be specified with or without leading zeros:
• “ww” or “WW”: week of year (with first week starting from Jan 1st) without/with
leading zeros.

Days
Day formats correspond to day of the year, business day of the year, day of the month, or
day of the week, in various numeric and text representations.
• “ddd” or “DDD”: day of year without/with leading zeros.
• “bbb” or “BBB”: business day of year without/with leading zeros (only counting
Monday-Friday).
• “dd” or “DD”: day of month without/with leading zeros.
• “day” or “DAY”: day of month with suffix, following the case of the format string
(“1st”, “2nd”, “3RD”).
• “w” or “W”: weekday number (1-7) where 1 is Monday.
Dates—109

• “wdy”, “Wdy”, or “WDY”: three-letter weekday abbreviation, following the case of


the format string (“Mon”, “Tue”, “WED”).
• “weekday”, “Weekday”, or “WEEKDAY”: full weekday name, following the case of the
format string (“monday”, “Tuesday”, “WEDNESDAY”).

Time (Hours/Minutes/Seconds)
The time formats correspond to hours (in 12 or 24 hour format), minutes, seconds, and frac-
tional sections, with or without leading zeros and with or without the AM/PM indicator
where appropriate.
• “hh” or “HH”: hour in 24-hour format without/with leading zeros.
• “hm” or “HM”: hour in 12-hour format without/with leading zeros.
• “am” or “AM”: two letter AM/PM indicator for 12-hour format, following the case of
the format string.
• “a” or “A”: single letter AM/PM indicator for 12-hour format, following the case of the
format string.
• “mi” or “MI”: minute, always with leading zeros.
• “ss.s”, “ss.s”, “ss.ss”, or “ss.sss”: seconds and tenths, hundreths, and thousandths-of-
a-second, with leading zeros. The capitalized forms of these formats (“SS”, “SS.S”, ...)
yield identical results.

Delimiters
You may use text to delimit the date format components:
• “f” or “F”: use frequency delimiter taken from the active, regular frequency workfile
page. The delimiter corresponds to the letter associated with the current workfile fre-
quency (“a”, “m”, “q”, ..., “A”, “M”, “Q”, ...), following the case of the format string,
or the colon (“:”), as determined by the Global Options setting (Options/General
Options.../Date representation).
• “?”: when used in an input date format, skips a single character of the input string. In
an output date format “?” will be passed to the output string.
On input, the”?” delimiter is useful for ignoring part of a date string or where a delim-
iter may be variable. For example, an input string "02:83" could be interpreted using
the format "MM:YY" to capture both month and year, or the format "??:YY" to capture
just the year.
• Other alphabetical characters are errors unless they are enclosed in square brackets
e.g. “[Q]”, in which case they are passed through to the output (for example, the
“standard-EViews” quarterly format is “YYYY[Q]Q”, where we use a four digit year
110—Chapter 5.Dates

identifier, followed by a “Q” delimiter/identifier, followed by a single digit for the


quarter “1990Q2”).
• All other characters (e.g., punctuation) are passed through to the input or output
without special interpretation.

Translating between Date Strings and Date Numbers


There are times when it is convenient to work with date strings, and times when it is easier
to work with date numbers.

For example, when we are describing or viewing a specific date, it is easier to use a “human
readable” date string such as “2002-Mar-20”, “3/20/2002”, or “March 20, 2002 12:23 pm”
than the date number 730928.515972.

Alternatively, since date strings are merely text representations of dates, working with date
numbers is essential when manipulating calendar dates to find elapsed days, months or
years, or to find a specific date and time 31 days and 36 hours from now.

Accordingly, translating between string representations of dates and date numbers is one of
the more important tasks when performing advanced operations with dates in EViews.
These translations occur in many places in EViews, ranging from the interpretation of date
strings in sample processing, to the spreadsheet display of series containing date numbers,
to the import and export of data from foreign sources.

In most settings, the translations take place automatically, without user involvement. For
example, when you enter a sample command of the form
smpl 1990q1 2000q4

EViews automatically converts the date strings into a range of date numbers. Similarly,
when you edit a series that contains date numbers, you typically will enter your data in the
form of a date string such as
"2002-Mar-20"

which EViews will automatically translate into a date number.

In other cases, you will specifically request a translation by using the built-in EViews func-
tions @datestr (to convert a date number to a string) and @dateval (to convert a date
string to a date number).

For example, the easiest way to identify the date 1,000 days after May 1, 2000 is first to con-
vert the string value “May 1, 2000” into a date number using @dateval, to manipulate the
date number to find the value 1000 days after the original date, and finally to convert the
resulting date number back into a string using @datestr (p. 824). See also “Formatted Con-
version” on page 114 and “Manipulating Date Numbers” on page 119 for additional details.

All translations between dates strings and date numbers involve one of two methods:
Dates—111

• First, EViews may perform a free-format conversion in which the date format is
inferred from the string values, in some cases other contextual information.
• Second, EViews may perform a formatted conversion in which the string representa-
tion of the dates is provided explicitly via a date format.

For the most part, you should find that free-format conversion is sufficient for most needs.
Nevertheless, in some cases the automatic handling of dates by EViews may not produce the
desired results. If this occurs, you should either modify any ambiguous date formats, or
specify an explicit formatted conversion to generate date numbers as necessary.

Free-format Conversion
EViews will perform free-format conversions between date strings and numbers whenever:
(1) there is an automatic translation between strings and numbers, or (2) when you use one
of the translation functions without an explicit date format.

When converting from strings to numbers, EViews will produce a date number using the
“most likely” interpretation of the date string. For the most part, you need not concern your-
self with the details of the conversion, but if you require additional detail on specific topics
(e.g., handling of date intervals, the implicit century cutoff for 2-digit years) see “Free-for-
mat Conversion Details” on page 124.

When converting from date numbers to strings, EViews will use the global default settings to
determine the default date format, and will display all significant information in the date
number.

Converting Unambiguous Date Strings to Numbers


The free-format conversion of unambiguous date strings (see “Date Strings” on page 105), to
numbers will produce identical results in all settings. The date string:
"March 3rd, 1950"

will be interpreted as the third day of the third month of the year A.D. 1950, and will yield
the date value 711918.0. Note that the date value is the smallest associated with the given
date, corresponding to 12 midnight.

Similarly, the date string:


"1980Q3"

is interpreted as the first instance in the third quarter of 1980. EViews will convert this string
into the date number representing the smallest date value in that quarter, 722996.0 (12 mid-
night on July 1, 1980).

If we specify a time string without a corresponding day,


"9:52PM"
112—Chapter 5.Dates

the day portion of the date is set to 0 (effectively, January 1, A.D. 1), yielding a value of
0.91111111 (see “Incomplete Date Numbers” on page 125) for details.

Consider also the following ambiguous date string:


"1 May 03"

While this entry may appear to be ambiguous since the “03” may reasonably refer to either
1903 or 2003, EViews resolves the ambiguity by assuming that if the two-digit year is greater
than or equal to 30, the year is assumed to be from the twentieth century, otherwise the year
is assumed to be from the twenty first century (see “Two-digit Years” on page 125 for discus-
sion). Consequently free-format conversion of two-digit years will produce consistent results
in all settings.

Converting Ambiguous Date Strings to Numbers


Converting from ambiguous date strings will yield context sensitive results. In cases involv-
ing ambiguity, EViews will determine the most likely translation format by examining sur-
rounding data or applicable settings for clues as to how the date strings should be
interpreted.

The following contextual information is used in interpreting ambiguous free-form dates:


• For implicit period notation (e.g., “1990:3”) the current workfile frequency is used to
determine the period.
• Choosing between ambiguous “mm/dd” or “dd/mm” formats is determined by exam-
ining the values of related date strings (i.e., those in the same series), user-specified
date/time display formats for a series or column of a spreadsheet, or by examining the
EViews global setting for date display, (Options/General Options.../Date representa-
tion).

To fix ideas, we consider a few simple examples of the use of contextual information.

If you specify an ambiguous sample string, EViews will use the context in which the sample
is used, the frequency of the workfile, to determine the relevant period. For example, given
the sample statement
smpl 90:1 03:3

and a quarterly workfile, the sample will be set from 1990q1 to 2003q3. If the workfile is
monthly, the sample will be set from January 1990 to March 2003.

Suppose instead that you are editing a series spreadsheet where your date numbers are dis-
played as dates strings using a specified format. In this setting, EViews allows you to enter
your values as date strings, instead of having to enter the underlying date numbers. In this
context, it is natural for EViews to use the current display format as a hint in interpreting
ambiguous data. For example, if the current display format is set to “Month dd, YYYY” then
an input of “2/3/4” or “@dateval("2/3/4")” will be interpreted as February the 3rd, 2004.
Dates—113

On the other hand, if the current display format is set to “YYYY-MM-DD” then the same
input will be interpreted as the March the 4th, 2002.

In settings where an entire series is provided to an EViews procedure, EViews is able to use
all of the values in the series to aid in determining the underlying data format. For example,
when an alpha series is provided as a date identifier for restructuring a workfile, EViews will
first scan all the values of the series in order to decide on the most likely format of all of the
data before converting the string in each element into a date number. If the first observation
of the series is an ambiguous “2/3/4” but a later observation is “3/20/95” then the “2/3/4”
will be interpreted as the 3rd of February 2004 since that is the only order of year, month
and day that is consistent with the “3/20/95” observation.

Conversely, when generating new series values with a genr or series assignment statement,
EViews processes observation individually and is therefore unable to obtain contextual
information to aid in interpreting ambiguous date strings. In this case, EViews will use the
global workfile setting for the Month/Day order in dates to determine the ordering of the
days and months in the string.

For example, when the expression


series dnums = @dateval("2/3/4")

is used to generate a series containing date values, EViews will interpret the value as Febru-
ary 3, 2004, if the global setting is Month/Day/Year, and March 2, 2004, if the global setting
is Day/Month/Year.
114—Chapter 5.Dates

Converting Date Numbers to Strings


EViews provides the @datestr (p. 824) function to translate a date number to a date string.
We describe the function in detail in “Formatted Conversion” on page 114, but for now, sim-
ply note that @datestr takes an optional argument describing the date format to be used
when exporting the string. If the optional argument is not provided, EViews will perform a
free-format conversion.

In performing the free-format conversion, EViews examines two pieces of information. First,
the global default settings for the Month/Day order in dates will be used to determine the
ordering of days and months in the string. Next, EViews examines the date values to be
translated and looks for relevant time-of-day information.

If there is no relevant time-of-day information in the date numbers (e.g., the non-integer por-
tions are all zero), EViews writes the string corresponding to the date using either the date
format
"dd/mm/yyyy"

or
"mm/dd/yyyy”

with preference given to the order favored in the global settings.

If there is relevant time-of-day information, EViews will extend the date format accordingly.
Thus, if days are favored in the ordering, and relevant hours (but not minutes and seconds)
information is present, EViews will use
"dd/mm/yyyy hh"

while if hours-minutes are present, the format will be


"dd/mm/yyyy hh:mi"

and so forth.

Formatted Conversion
While the free-format conversions will generally produce the desired results, there may be
times when you want to exercise precise control over the conversion. EViews will perform a
formatted conversion between date strings and date numbers whenever you use the @dat-
eval (p. 825) or @datestr (p. 824) functions with the optional second argument specifying
an explicit date format.

To convert a date string into a date number using a date format, you should use the @dat-
eval function with two arguments. The first argument must be a valid date string, and the
second must be the corresponding date format string. If you omit the optional second argu-
ment, EViews will perform a free-format conversion.
Dates—115

• @dateval(str[, fmt]): takes the string str and evaluates it to a date number using the
optional date format string, fmt.
See @dateval (p. 825).

A few simple examples will illustrate the wide range of string to date number conversions
that are possible using @dateval and a date format. The simplest format strings involve the
standard month/day/year date descriptions:
@dateval("12/1/1999", "mm/dd/yyyy")

will return the date number for December 1, 1999 (730088),


@dateval("12/1/1999", "dd/mm/yyyy")

returns the date number for January 12, 1999 (729765). Here we have changed the interpre-
tation of the date string from “American” to “European” by reversing the order of the parts
of the format string.

Likewise, we may find the first date value associated with a given period
@dateval("1999", "yyyy")

returns the value 729754.0 corresponding to 12 midnight on January 1, 1999, the first date
value for the year 1999.

Conversion of an broad range of date strings is possible by putting together various date for-
mat string components. For example,
@dateval("January 12, 1999", "Month dd, yyyy")

returns the date number for 12 midnight on January 12, 1999 (729765), while
@dateval("99 January 12, 9:37 pm", "yy Month dd, hm:mi am")

yields the value 729765.900694 corresponding to the same date, but at 9:37 in the evening.
In this example, the “hm:mi” corresponds to hours (in a 12 hour format, with no leading
0’s) and minutes, and the “am” indicates that there is an indicator for “am” and “pm”. See
“Date Strings” on page 105 and “Date Formats” on page 106 for additional details.

To translate a date number to a date string using a date format, you should use the @dat-
estr function with two arguments. The first argument must be a valid date number, and the
second must be a date format string describing a string representation of the date.
• @datestr(date_val[, fmt]): converts the date number into a string, using the optional
date format fmt. If a format is not provided, EViews will use a default method (see
“Converting Date Numbers to Strings” on page 114).
See @datestr (p. 824).

For example,
@datestr(730088,"mm/dd/yy")
116—Chapter 5.Dates

will return “12/1/99”,


@datestr(730088,"DD/mm/yyyy")

will return “01/12/1999”, and


@datestr(730088,"Month dd, yyyy")

will return “December 1, 1999”, and


@datestr(730088,"w")

will produce the string “3”, representing the weekday number for December 1, 1999. See
“Date Numbers” on page 106 and “Date Formats” on page 106 for additional details.

Translating Ordinary Numbers into Date Numbers


While date information is most commonly held in the form of date strings or date numbers,
one will occasionally encounter data in which a date is encoded as a (non-EViews format)
numeric value or values. For example, the first quarter of 1991 may be given the numeric
representation of 1991.1, or the date “August 15, 2001” may be held in the single number
8152001, or in three numeric values 8, 15, and 2001.

The @makedate function is used to translate ordinary numbers into date numbers. It is sim-
ilar to @dateval but is designed for cases in which your dates are encoded in one or more
numeric values instead of date strings:
• @makedate(arg1[, arg2[,arg3]], fmt): takes the numeric values given by the argu-
ments arg1, and optionally, arg2, etc. and returns a date number using the required
format string, fmt. Only a subset of all date formats are supported by @makedate.
If more than one argument is provided, the arguments must be listed from the lowest
frequency to the highest, with the first field representing either the year or the hour.
See @makedate (p. 960).

The simplest form of @makedate involves converting a single number into a date or a time.
The following are the supported formats for converting a single number into a date value:
• “yy” or “yyyy”: two or four-digit years.
• “yys” or “yyyys”: year*10 + half-year.
• “yy.s” or “yyyy.s”: year + half-year/10.
• “yyq” or “yyyyq”: year*10 + quarter.
• “yy.q” or “yyyy.q”: year + quarter/10.
• “yymm” or “yyyymm”: year*10 + month.
• “yy.mm” or “yyyy.mm”: year + month/10.
• “yyddd” or “yyyyddd”: year*1000 + day in year.
Dates—117

• “yy.ddd” or “yyyy.ddd”: year + day in year/1000.


• “yymmdd” or “yyyymmdd”: year*10000 + month*100 + day in month.
• “mmddyy”: month*10000 + day in month*100 + two-digit year.
• “mmddyyyy”: month*100000 + day in month*10000 + four-digit year.
• “ddmmyy”: day in month*10000 + month*100 + two-digit year.
• “ddmmyyyy”: day in month*1000000 + month*10000 + four-digit year.

The following formats are supported for converting a single number into intraday values:
• “hh”: hour in day (in 24 hour units)
• “hhmi”: hour*100 + minute.
• “hhmiss”: hour*10000 + minute*100 + seconds.

Note that the @makedate format strings are not case sensitive, since the function requires
that all non-leading fields must have leading zeros where appropriate. For example, when
using the format “YYYYMMDD”, the date March 1, 1992 must be encoded as 19920301, and
not 199231, 1992031, or 1992301.

Let us consider some specific examples of @makedate conversion of a single number. You
may convert a numeric value for the year into a date number using a format string to
describe the year. The expressions:
@makedate(1999, "yyyy")
@makedate(99, "yy")

both return the date number 729754.0 corresponding to 12 midnight on January 1, 1999.
Similarly, you may convert a numeric value into the number of hours in a day using expres-
sions of the form,
@makedate(12, "hh")

Here, EViews will return the date value 0.5 corresponding to 12 noon on January 1, A.D. 1.
While this particular date value is not intrinsically of interest, it may be combined with
other date values to obtain the value for a specific hour in a particular day. For example
using date arithmetic, we may add the 0.5 to the 729754.0 value (12 midnight, January 1,
1999) obtained above, yielding the date value for 12 noon on January 1, 1999. We consider
these sorts of operations in greater detail in “Manipulating Date Numbers” on page 119.

If your number contains “packed” date information, you may interpret the various compo-
nents using @makedate with an appropriate format string. For example,
@makedate(199003, "yyyymm")
@makedate(1990.3, "yyyy.mm")
@makedate(1031990, "ddmmyyyy")
118—Chapter 5.Dates

@makedate(30190, "mmddyy")

all return the value 726526.0, representing March 1, 1990.

Cases where @makedate is used to convert more than one argument into a date or time are
more limited and slightly more complex. The arguments must be listed from the lowest fre-
quency to the highest, with the first field representing either the year or the hour, and the
remaining fields representing sub-periods. The valid date format strings for the multiple
argument @makedate are a subset of the date format strings, with components applied
sequentially to the numeric arguments:
• “yy s” or “yyyy s”: two or four-digit year and half-year.
• “yy q” or “yyyy q”: year and quarter.
• “yy mm” or “yyyy mm”: year and month.
• “yy ddd” or “yyyy ddd”: year and day in year.
• “yy mm dd” or “yyyy mm dd”: year, month, and day in month.

Similarly, the valid formats for converting multiple numeric values into a time are:
• “hh mi”: hour*100 + minute.
• “hh mi ss”: hour*10000 + minutes*100 + seconds.

For convenience, the non-space-delimited forms of these format strings are also supported
(e.g., “yymm”, and “hhmi”).

For example, the expressions,


@makedate(97, 12, 3, "yy mm dd")
@makedate(1997, 12, 3, "yyyymmdd")

will return the value 729360.0 corresponding to midnight on December 3, 1997. You may
provide a subset of this information so that
@makedate(97, 12, "yymm")

returns the value 729358.0 representing the earliest date and time in December of 1997 (12
midnight, December 1, 1997). Likewise,
@makedate(1997, 37, "yyyy ddd")

yields the value 729060.0 (February 6, 1997, the 37th day of the year) and
@makedate(14, 25, 10, "hh mi ss")

returns the value 0.600810185 corresponding to 2:25:10 pm on January 1, A.D. 1.


Dates—119

It is worth pointing out that in the examples above, the numeric arguments are entered from
lowest frequency to high, as required. The following example, in which days appear before
months and years, is not a legal specification
@makedate(7, 10, 98, "dd mm yy")

and will generate an error reporting a “Bad date format”.

Lastly, we note that limitations on the date formats supported by @makedate imply that in
some cases, you are better off working with strings and the @dateval function. In cases,
where @makedate does not support a desired conversion, you should consider converting
your numbers into strings, performing string concatenation, and then using the richer set of
@dateval conversions to obtain the desired date values.

Manipulating Date Numbers


One of the most important reasons for holding your date information in the form of date
numbers is so that you may perform sophisticated calendar operations.

Date Operators
Since date values are simply double precision numbers, you may perform standard mathe-
matical operations using these values. While many operations such as division and multipli-
cation do not preserve the notion of a date number, you may find addition and subtraction
and relational comparison of date values to be useful tools.

If, for example, you add 7 to a valid date number, you get a value corresponding to the same
time exactly seven days later. Adding 0.25 adds one-quarter of a day (6 hours) to the current
time. Likewise, subtracting 1 gives the previous day, while subtracting 0.5 gives the date
value 12 hours earlier. Taking the difference between two date values yields the number of
days between the two values.

While using the addition and subtraction operators is valid, we strongly encourage you to
use the EViews specialized date functions since they allow you to perform arithmetic at var-
ious frequencies (other than days), while taking account of irregularities in the calendar (see
“Functions for Manipulating Dates” on page 120).

Similarly, while you may round a date number down to the nearest integer to obtain the first
instance in the day, or you may round down to a given precision to find the first instance in
a month, quarter or year, the built-in functions provide a set of simple, yet powerful tools for
working with dates.

Note further that all of the relational operators are valid for comparing date numbers. Thus,
if two date numbers are equal, the “=”, “>=”, and “<=” relational operators all return a
1, while the “<>”, “>”, and “<” comparison operators return a 0. If two date numbers
are not equal, “<>” returns a 1 and “=” returns a 0. If the first date number is less than a
second date number, the corresponding first date precedes the second in calendar time.
120—Chapter 5.Dates

Functions for Manipulating Dates


EViews provides several functions for manipulating dates that take date numbers as input
and return numeric values that are also date numbers. These functions may be used when
you wish to find a new date value associated with a given date number, for example, a date
number 3 months before or 37 weeks after a given date and time.

The functions described below all take a time unit string as an argument. As the name sug-
gests, a time unit string is a character representation for a unit of time, such as a month or a
year. The valid time unit string values are: “A” or “Y” (annual), “S” (semi-annual), “Q”
(quarters), “MM” (months), “WW” (weeks), “DD” (days), “B” (business days), “HH”
(hours), “MI” (minutes), “SS” (seconds).

There are three primary functions for manipulating a date number:


• @dateadd(date1, offset[, u]): returns the date number given by date1 offset by offset
time units as specified by the time unit string u. If no time unit is specified, EViews
will use the workfile regular frequency, if available.
Suppose that the value of date1 is 730088.0 (midnight, December 1, 1999). Then we
can add and subtract 10 days from the date by using the functions
@dateadd(730088.0, 10, "dd")
@dateadd(730088.0, -10, "dd")
which return 730098.0 (December 11, 1999) and (730078.0) (November 21, 1999).
Note that these results could have been obtained by taking the original numeric value
plus or minus 10.
The @dateadd function allows for date offsets specified in various units of time. For
example, to add 5 weeks to the existing date, simply specify “W” or “WW” as the
time unit string, as in
@dateadd(730088.0, 5, "ww")
which returns 730123.0 (January 5, 2000).
See @dateadd (p. 815).
• @datediff(date1, date2[, u]): returns the number of time units between date1 and
date2, as specified by the time unit string u. If no time unit is specified, EViews will
use the workfile regular frequency, if available.
Suppose that date1 is 730088.0 (December 1, 1999) and date2 is 729754.0 (January 1,
1999), then,
@datediff(730088.0, 729754.0, "dd")
returns 334 for the number of days between the two dates. Note that this is result is
simply the difference between the two numbers.
Dates—121

The @datediff function is more powerful in that it allows us to calculate differences


in various units of time. For example, the expressions
@datediff(730088.0, 729754.0, "mm")
@datediff(730088.0, 729754.0, "ww")
return 11 and 47 for the number of months and weeks between the dates.
See @datediff (p. 817).
• @datefloor(date1, u[, step]): finds the first possible date number in the given time
unit, as in the first possible date value in the current quarter, with an optional step
offset.
If step is omitted, the frequency will use a step of 1 so that by default, @datefloor
will find the beginning of the period defined by the time unit.
Suppose that date1 is 730110.5 (12 noon, December 23, 1999). Then the @datefloor
values
@datefloor(730110.5, "dd")
@datefloor(730110.5, "mm")
yield 730110.0 (midnight, December 23, 1999) and 730088.0 (midnight, December 1,
1999), since those are the first possible date values in the current day and month.
Note that the first value is simply the integer portion of the original date number, but
that the latter required more complex analysis of the calendar.
Likewise, we can find the start of any corresponding period by using different time
units:
@datefloor(730098.5, "q")
@datefloor(730110.5, "y", 1)
returns 730027.0 (midnight, October 1, 1999), and 729754.0 (midnight, January 1,
1999. Notice that since the latter example used an offset value of 1, the result corre-
sponds to the first date value for the year 1999, which is the start of the year following
the actual value.
See @datefloor (p. 820).

Extracting Information from Date Numbers


Given a date number you may wish to extract numeric values associated with a portion of
the value. For example, you might wish to know the value of the month, the year, or the day
in the year associated with a given date value. EViews provides the @datepart function to
allow you to extract the desired information.
• @datepart(date1, u): returns a numeric part of a date value given by u, where u is a
time unit string.
122—Chapter 5.Dates

See @datepart (p. 823).

Consider the date1 date value 730110.5 (noon, December 23, 1999). The @datepart values
for
@datepart(730110.5, "dd")
@datepart(730110.5, "w")
@datepart(730110.5, "ww")
@datepart(730110.5, "mm")
@datepart(730110.5, "yy")

are 23 (day of the month), 1 (day in the week), 52 (week in the year), 12 (month in the
year), and 99 (year), respectively.

Note that the numeric values returned from @datepart are not themselves date values, but
may be used with @makedate to create date values.

Special Date Functions


In addition to the functions that convert strings or numbers into date values, EViews pro-
vides the following special ways to obtain one or more date values of interest.
• @now: returns the date number associated with the current time.

The remaining functions return information for each observation in the current workfile.
• @date: returns the date number corresponding to every observation in the current
workfile.
• @year: returns the four digit year in which the current observation begins. It is equiv-
alent to @datepart(@date, "YYYY")
• @quarter: returns the quarter of the year in which the current observation begins. It
is equivalent to @datepart(@date, "Q").
• @month: returns the month of the year in which the current observation begins. It is
equivalent to @datepart(@date, "MM").
• @day: returns the day of the month in which the current observation begins. It is
equivalent to @datepart(@date, "DD").
• @weekday: returns the day of the week in which the current observation begins,
where Monday is given the number 1 and Sunday is given the number 7. It is equiva-
lent to @datepart(@date, "W").
• @hour: returns the current observation hour as an integer. For example, 9:30AM
returns 9, and 5:15PM returns 17.
Dates—123

• @minute: returns the current observation minute as an integer. For example, 9:30PM
returns 30.
• @second: returns the current observation second as an integer.
• @hourf: returns the current observation time as a floating point hour. For example,
9:30AM returns 9.5, and 5:15PM returns 17.25.
• @strdate(fmt): returns the set of workfile row dates as strings, using the date format
string fmt. See “Date Formats” on page 106 for a discussion of date format strings.

The @date function will generally be used to create a series containing the date value asso-
ciated with every observation, or as part of a series expression involving date manipulation.
For example:
series y = @date
series x = @dateadd(@date, 12, "ww")

which generates a series containing the date values for every observation, and the date val-
ues for every observation 12 weeks from the current values.

@strdate should be used when you wish to obtain the date string associated with every
observation in the workfile—for example, to be used as input to an alpha series. It is equiv-
alent to using the @datestr function on the date number associated with every observation
in the workfile.

Additional series functions involving dates may be listed in “Workfile Functions” on


page 696.

Free-format Conversion Formats


EViews supports the free-format conversion of a wide variety of date strings in which the
string is analyzed for the most likely corresponding date.

Any of the following date string types are allowed:

Day, month, year


• “"YYYY-MM-DD"” (IEEE, with the date enclosed in double quotes)
• “dd/mm/yy” (if American, “mm/dd/yy” instead)
• “dd/mm/yyyy” (if American, “mm/dd/yyyy” instead)
• “yyyy/mm/dd”
• “dd/mon/yy”
• “dd/mon/yyyy”
• “yyyy/mon/dd”
124—Chapter 5.Dates

• “ddmmyy” (if American, “mmddyy”)


• “ddmmyyyy” (if American, “mmddyyyy”)

The resulting date values correspond to the first instance in the day (12 midnight).

Month in year
• “mon/yy”
• “mon/yyyy”
• “yy/mon”
• “yyyy/mon”

The results are rounded to the first instance in the month (12 midnight of the first day of the
month).

Period in year
• “yyyy[S|Q|M|W|B|D|T|F|:]period”
• “yy[S|Q|M|W|B|D|T|F|:]period”

The date value is rounded to the first instance in the period in the year

Whole year
• “yyyy[A]”. The “A” is generally optional, but required if current WF is undated.
• “yy[A]”. The “A” is generally optional, but required if current WF is undated.

The date value is rounded to the first instance in the year (12 midnight on January 1).

Free-format Conversion Details


Note that the following conventions may be used in interpreting ambiguous free-form dates.

Dates and Date Intervals


A date in EViews is generally taken to represent a single point in calendar time. In some con-
texts, however, a date specification is used to refer to a range of values contained in a time,
which can be referred to as an interval.

When a date specification is treated as an interval, the precision with which the date is spec-
ified is used to determine the duration of the interval. For example, if a full day specification
is provided, such as “Oct 11 1980”, then the interval is taken to run from midnight at the
beginning of the day to just before midnight at the end of the day. If only a year is specified,
such as “1963”, then the interval is taken to run from midnight on the 1st of January of the
year to just before midnight on the 31st of December at the end of the year.
Dates—125

An example where this is used is in setting the sample for a workfile. In this context, pairs of
dates are provided to specify which observations in the workfile should be included in the
sample. The pairs of dates are provided are processed as intervals, and the sample is defined
to run from the start of the first interval to the end of the second interval. As an example, if
the sample “1980q2 1980q2” is specified for a daily file, the sample will include all observa-
tions from April 1st 1980 to June 30th 1980 inclusive.

Incomplete Date Numbers


An EViews date number can be used to represent both a particular calendar day, and a par-
ticular time of day within that day. If no time of day is specified, the time of day is set to
midnight at the beginning of the day.

When no date is specified, the day portion of a date is effectively set to 1st Jan A.D. 1. For
example, the date string “12 p.m.” will be translated to the date value 0.5 representing 12
noon on January 1, A.D. 1. While this particular date value is probably not of intrinsic inter-
est, it may be combined with other information to obtain meaningful values. See “Manipu-
lating Date Numbers” on page 119

Two-digit Years
In general, EViews interprets years containing only two digits as belonging to either the
twentieth or twenty-first centuries, depending on the value of the year. If the two digit year
is greater than or equal to 30, the year is assumed to be from the twentieth century and a
century prefix of “19” is added to form a four digit year. If the number is less than 30, the
year is assumed to be from the twenty first century and a century prefix of “20” is added to
form a four digit year.

Note that if you wish to refer to a year after 2029 or a year before 1930, you must use the full
four-digit year identifier.

Because this conversion to four digit years is generally performed automatically, it is not
possible to specify years less than A.D. 100 using two digit notation. Should the need ever
arise to represent these dates, such two digit years can be input directly by specifying the
year as a four digit year with leading zeros. For example, the 3rd of April in the year A.D. 23
can be input as “April 3rd 0023”.

Implicit Period Notation


In implicit period notation (e.g., “1990:3”), the current workfile frequency is used to deter-
mine the period.

American vs. European dates


When performing a free-format conversion in the absence of contextual information suffi-
cient to identify whether data are provided in “mm/dd” or “dd/mm” format, the global
126—Chapter 5.Dates

workfile setting for the Options/Dates & Frequency Conversion.../Month/Day order in


dates (“Date Representation” on page 2552 of the User’s Guide I) will be used to determine
the ordering of the days and months in the string.

For example, the order of the months and years is ambiguous in the date pair:
1/3/91 7/5/95

so EViews will use the default date settings to determine the desired ordering. We caution
you, however, that using default settings to define the interpretation of date strings is not a
good idea since a given date string may be interpreted in different ways at different times if
your settings change. You may instead use the IEEE standard format, “YYYY-MM-DD” to
ensure consistent interpretation of your daily date strings. The presence of a dash in the for-
mat means that you must enclose the date in quotes for EViews to accept this format. For
example:
smpl "1991-01-03" "1995-07-05"

will always set the sample to run from January 3, 1991 and July 5, 1995.

Time of Day
Free-format dates can also contain optional trailing time of day information which must fol-
low the pattern:
hh[[[[[:mi:]ss].s]s]s][am|AM|pm|PM]

where “[]” encloses optional portions or the format and “|” indicates one of a number of
possibilities. In addition, either the “am” or “pm” field or an explicit minute field must be
provided for the input to be recognized as a time. An hour by itself is generally not suffi-
cient.

The time of day in an EViews date is accurate up to a particular millisecond within the day,
although any date can always be displayed at a lower precision. When displaying times at a
lower precision, the displayed times are always rounded down to the requested precision,
and never rounded up.

When both a day and a time of day are specified as part of a date, the two can generally be
provided one after the other with the two fields separated by one or more spaces. If, how-
ever, the date is being used in a context where EViews does not permit spaces between input
fields, a single letter “t” can also be used to separate the day and time so that the entire date
can be contained in a single word, e.g. “1990-Jan-03T09:53”.

Time Zones
There are a related set of functions that you may use that provide information on time-
zones: @localt (p. 946), @tz (p. 1155), @tzlist (p. 1155), @tzspec (p. 1156), and @utc
(p. 1173).
Dates—127
128—Chapter 5.Dates
Chapter 6. EViews Programming

EViews’ programming features allow you to create and store commands in programs that
automate repetitive tasks, or generate a record of your research project.

You may, for example, write a program containing commands that analyze the data from
one industry, and then have the program perform the analysis for a number of other indus-
tries. You can also create a program containing the commands that take you from the cre-
ation of a workfile and reading of raw data, through the calculation of your final results, and
construction of presentation graphs and tables.

The remainder of this chapter outlines the basics of EViews programming. If you have expe-
rience with computer programming and batch or macro processing, you will find most of the
features of the EViews language to be quite familiar. At the same time, non-programmers
should feel welcome to examine the material as you need not have any experience with pro-
gramming to take advantage of these powerful features.

Program Basics
What is a Program?
A program is simply a text file containing EViews commands. It is not an EViews object in a
workfile. It exists as a file on your computer hard disk, generally with a “.PRG” extension.

Creating a Program
To create a new program, click File/New/Program. You will see a standard text editing win-
dow where you can type in the lines of the program. You may also open the program win-
dow by typing program in the command window, followed by an optional program name.
For example
program firstprg

opens a program window named “FIRSTPRG”. Program names should follow standard
EViews rules for file names.

Program Formatting
As noted earlier, an EViews program is a text file, consisting of one or more lines of text.
Generally, each line of a program corresponds to a single EViews command, so you may
enter the text for each command and terminate the line by pressing the ENTER key.

If a program line is longer than the current program window, EViews will, by default, autow-
rap the text of the line. Autowrapping alters the appearance of the program line by display-
ing it on multiple lines, but does not change the contents of the line. While resizing the
130—Chapter 6.Program Basics

window will change the autowrap position, the text remains unchanged and is still con-
tained in a single line. You may turn off autowrapping in programs via Options/General
Options/Programs and deselecting the Enable word wrap check box, or by clicking the
Wrap +/- button on the program window.

When autowrapping is turned off via the option menu, you may elect to show program line
numbers in your program window by selecting Display line numbers. You may then right-
click anywhere in your program and select Go To Line... to jump directly to a specific line
number.

If you desire greater control over the appearance of your lines, you can manually break long
lines using the ENTER key, and then use the underscore continuation character “_” as the
last character on the line to join the multiple lines. For example, the three separate lines of
text
equation eq1.ls _
y x c _
ar(1) ar(2)

are equivalent to the single line


equation eq1.ls y x c ar(1) ar(2)

formed by joining the lines at the continuation character. We emphasize that the “_” must
be the very last character in the line.

The apostrophe “'” is the comment character in programs. You may place the comment
character anywhere in a line to treat all remaining characters in the line as a comment which
will be ignored when executing the program command.
equation eq1.ls y x c ar(1) ar(2) ’ this is a comment

A block of lines may be commented or uncommented in the EViews program file editor by
highlighting the lines, right-mouse clicking, and selecting Comment Selection or Uncom-
ment Selection.

You can instruct EViews to automatically format your program by selecting the lines to
which you wish to apply formatting, right-mouse clicking and selecting Format Selection.
Automatic formatting will clean up the text in the selection, and will highlight the structure
of the program by indenting lines of code inside loops, if conditions and subroutines, etc.
You should find that automatic formatting makes your programs easier to read and edit.

You may elect to have EViews automatically indent your program as you type by changing
the Indent option in the main EViews options menu (Options/General Options/Programs).
Program Basics—131

Saving a Program
After you have created and edited your program, you will probably want to save it. Press the
Save or SaveAs button on the program window toolbar. When saved, the program will have
the extension “.PRG”.

If saving your program will overwrite an existing program file and you have instructed
EViews to make backup copies (“Programs,” on page 2554 of User’s Guide I), EViews will
automatically create the backup. The backup copy will have the same name as the file, but
with the first character in the extension changed to “~”.

Snapshots for Programs


Managing snapshots for an EViews program is similar to workfiles (“Snapshot Backups,” on
page 67). The program window has a Snapshot button to perform a manual snapshot.

Viewing Snapshots for Programs


To view available snapshots for a program, right-click in the program window and select
Snapshots…
132—Chapter 6.Program Basics

Clicking on a previous snapshot will display a text compare view that highlights any differ-
ences between the two versions.

You can also right-click any snapshot and select Open… (or simply double-click the node)
to open the snapshot in its own program window.

Note that automatic snapshots are suspended when an EViews program is actively running.
Program Basics—133

Saving the Command Window


One convenient method of creating a program is to execute several commands using the
EViews command window and then save the history of those commands to a program file.
Click in the command window then select File/Save As... from the main EViews menu.
EViews will prompt you to save the command log as a text file. Simply save the file with the
“.PRG” extension.

You may then edit the program file and save the edited version in the usual fashion.

Encrypting a Program
EViews offers you the option of encrypting a program file so that you may distribute it to
others in a form where they may not view the original text. Encrypted files may be opened
and the program lines may be executed, but the source lines may not be viewed. To encrypt
a program file simply click on the Encrypt button on the program window.

EViews will create an untitled program containing the contents of the original program, but
with only the visible text “Encrypted program”. You may save this encrypted program in the
usual fashion using Save or SaveAs.

Note that once a program is encrypted it may not be unencrypted; encryption should not be
viewed as a method of password protecting a program. You should always keep a separate
copy of the original source program. To use an encrypted program, simply open it and run
the program in the usual fashion.

Opening a Program
To load a program file previously saved on disk, click on File/Open/Program..., navigate to
the appropriate directory, and click on the desired name. You may also drag an EViews pro-
gram file onto the EViews window to open it. Alternatively, from the command line, you
may type the keyword open followed by the full program name, including the file extension
“.PRG”. By default, EViews will look for the program in the default directory, but you may
include the full path to the file and enclosed the entire name in quotations, if desired. For
example, the commands:
open mysp500.prg
open "c:\mywork is here\eviews\myhouse.prg"

open the file “Mysp500.PRG” in the default EViews directory, and “Myhouse.PRG” located
in the directory “c:\mywork is here\eviews”.

Executing a Program
Executing a program is the process of running all of the commands in a program file.
134—Chapter 6.Program Basics

Note that EViews commands can be executed in two distinct ways. When you enter and run,
line by line, a series of commands in the command window, we say that you are working in
interactive mode. Alternatively, you can type all of the commands in a program and execute
or run them collectively as a batch of commands. When you run the commands from a pro-
gram file, we say that you are in (non-interactive) program mode or batch mode.

There are several ways to execute an EViews program:


• The easiest method is by pushing the Run button on an open program window and
entering settings in the Run Program dialog.
• Alternately, you may use the run or exec command to execute a program.
• You may use external automation tools to run EViews and execute a program from
outside of the EViews application environment.
• You may select a set of subset of lines to execute and run the selected lines.

The Run Program Dialog


To run a program from a dialog, click on
the Run button on the program window.
The Run dialog opens.

The default run options are taken from


the global settings (“Programs” on
page 2554 of User’s Guide I), but may be
overridden on a one-time basis using the
dialog settings or command options. For
purposes of discussion, we will assume
that the global options are set to their
out-of-the-box values.

The Program name or path edit field


will show the name and in some cases,
path, of the program you are running. You may enter a file specification to instruct EViews
to look for a particular program.

The Program arguments edit field is used to define special string variables that will be
passed to your program when it is running. See “Program Arguments” on page 155 of User’s
Guide I for details.

The Runtime errors section allows you to modify the behavior of the program when it
encounters an error. By default, when EViews encounters an error, it will immediately termi-
nate the program and display a message. If you enter a number into the Maximum errors
before halting field, EViews will, if possible, continue to execute the program until the max-
imum number of errors is reached. If it encounters a serious error that makes it impossible
Program Basics—135

to continue, EViews will halt the program even if the maximum number of errors is not
reached. See “Execution Errors” on page 165.

If the Compatibility section checkbox labeled Version 4 compatible variable substitution


and program boolean comparisons is selected, EViews will use the variable substitution
behavior found in EViews 4 and earlier. To support the use of alpha series, EViews 5 and
subsequent versions altered the way that % substitution variables are evaluated in expres-
sions. To return to EViews 4 compatible rules for substitution, you may either use this
checkbox or include a “MODE VER4” statement in your program. See “Version 4 Compati-
bility Notes” on page 188 and “Program Modes” on page 151 for additional discussion.

Lastly, you may select the Save options as default checkbox to update your global options
with the specified settings. Alternately, you may change the global options from the
Options/General Options.../Programs/General dialog.

The Run and Exec Commands


You may use the run command to execute a program from the EViews command window.
Simply enter the keyword run along with any options, followed by a program file specifica-
tion and any arguments (see run (p. 581)).

You may run a program by entering the run command, followed by the name of the program
file:
run mysp500

or, using an explicit path,


run c:\eviews\myprog arg1 arg2 arg3

Note that use of the “.PRG” extension is not required since EViews will automatically
append one to your specification.

The default run options will be taken from the global settings (“Programs” on page 2554 of
User’s Guide I), but may be overridden using the command options. For example, you may
use the “v” or “verbose”options to run the program in verbose mode, and the “q” or “quiet”
options to run the program in quiet mode. If you include a number as an option, EViews will
use that number to indicate the maximum number of errors encountered before execution is
halted:
run(v, 500) mysp500

or
run(q, ver4) progarg

Alternatively, you may modify your program to include statements for quiet or verbose
mode, and statements to specify version compatibility. For example, to return to EViews 4
compatible rules for substitution, you may use the “ver4” option or include a “MODE VER4”
136—Chapter 6.Program Basics

statement in your program. See “Version 4 Compatibility Notes” on page 188 and “Program
Modes” on page 151 for additional discussion.

You may provide a list of program arguments after the name of the program. These argu-
ments will be passed on to the program as %0, %1 etc. See “Program Arguments” on
page 155 for more details.

Program options may be passed on to the program by entering them, surrounded by paren-
thesis immediately after the name of the program. See “Program Options” on page 156 for
details.

For example:
run myprog(opt1, opt2, opt3=k) arg0 arg1 arg1

will run the program MYPROG passing on the options OPT1, OPT2, OPT3=k as options,
and ARG0, ARG1 and ARG1 as arguments (%0, %1 and %2 respectively).

You may have launch EViews and run a program automatically on startup by choosing File/
Run from the menu bar of the Windows Program Manager or Start/Run in Windows and
then typing “eviews”, followed by the name of the program and the values of any argu-
ments. If the program has as its last line the command exit, EViews will close following the
execution of the program.

The exec command is similar to the run command. It can also be used to execute a pro-
gram file. The main differences between run and exec commands are the default directory
they will run from, and the behavior when returning from executing a program. For more
details see “Multiple Program Files” on page 167.

External Automation Tools


Lastly, you may use external automation tools to run EViews and execute a program from
outside of the EViews application environment. In particular, EViews may be used as a COM
Automation server so that an external program or script may launch and control EViews pro-
grammatically. See “EViews COM Automation Server” on page 195 and the EViews COM
Automation Server whitepaper, available from our website www.eviews.com/download/
download.html, for additional discussion.

Stopping a Program
Pressing the ESC or F1 keys halts execution of a program. It may take a few seconds for
EViews to respond to the halt command.

Programs will also stop when they encounter a stop command, when they reach the maxi-
mum number of errors, when they encounter a non-recoverable error in a program state-
ment, or when they finish processing a file that has been executed via a run statement.

If you include the exit keyword in your program, the EViews application will close.
Program Basics—137

Running Part of a Program


You may choose to only run part of your program by highlight the lines you wish to run,
then right-clicking and selecting Run Selected. EViews will then execute only the selected
line of code as a new program.

You should note that there are potential pitfalls when using Run Selected. The first is that
no arguments or options can be passed into the selected lines of code. If the selected lines
rely on program arguments or options, they will fail to execute properly. Similarly, any pro-
gram variables (“Program Variables” on page 143) declared outside of the selected lines may
not be initialized properly when the selected lines are run. Finally, any subroutines declared
outside of the selected lines of code cannot be called, since they do not exist in the selected
code.

Alternately, you may use add the stop command to your EViews program to halt execution
at a particular place in the program file.

Program Debugging
EViews offers tools for debugging to help you locate the source of problems. These tools
allow you to run programs until they hit breakpoints on specific lines and then examine the
state of your workfile at those breakpoints.

Setting and Clearing Breakpoints


Open the EViews program file and set the breakpoint by clicking to the left of the desired
line. A red dot will appear:
138—Chapter 6.Program Basics

Clicking on a red dot clears that breakpoint.

Starting a Debugging Session


To begin debugging the program, click the Debug button in the toolbar and enter any pro-
gram arguments, choose whether to Log dependencies, and if desired change the Maxi-
mum errors before halting. Click on OK.

EViews will start program execution and open the debugging pane. There are three tabs in
the pane: Breakpoints, Watch, and Callstack.

Stopping at a Breakpoint
When the program reaches an active breakpoint, the execution will pause at the red dot,
now highlighted in yellow:
Program Basics—139

At this point you can look at the Breakpoints, Callstack, or Watch windows for more infor-
mation.
• Breakpoints shows all defined breakpoints. Toggling the checkbox next to a break-
point name inactivates or reactivates it.
• Callstack displays the current line of the active files and subroutines of the program.
• Watch presents the values of program and replacement variables.

Additionally, you may open EViews objects such as series or equations to examine their cur-
rent states.

Button Bar
Resume continues program execution until the next breakpoint is reached. Step executes
the current line. Run continues program execution to completion, ignoring any remaining
breakpoints. Stop cancels program execution.

Restrictions during Debugging


During a debugging session, you will not be able to close any windows opened by the pro-
gram since this could negatively affect its execution.

Program Dependency Logging


EViews 14 has a new feature to automatically log a program’s external dependencies: files
(as workfiles, Excel files, CSV files, etc), databases, and other programs (as includes and
execs). To use it, check the Log Dependencies checkbox in the Run Program dialog:
140—Chapter 6.Program Basics

A new Program Dependencies window will appear showing the type, filename, and path of
all the external dependencies detected during the run.
Simple Programs—141

The above image shows the dependence on the external program files “xy.prg,” “wz.prg,”
and “z22.prg,” the workfiles “tq.wf1” and “untitled.wf1,” and the database “dbtest.edb,”
along with the line numbers producing these dependencies.

Simple Programs
The simplest program is just a list of EViews commands. Execution of the program is equiv-
alent to typing the commands one-by-one into the command window.

While you may execute the commands by typing them in the command window, you could
just as easily open a program window, type in the commands and click on the Run button.
Entering commands in this way has the advantage that you can save the set of commands
for later use, and execute the program repeatedly, making minor modifications each time.
(Note that you may combine the two methods by entering the commands in the command
window and then save them to a file as described in “Saving the Command Window” on
page 133.)

Since an EViews program is a collection of commands, familiarity with the EViews com-
mand language is an essential part of programming. The command language may be split
into four different groups in EViews.
• General commands create, structure and manipulate workfiles (including importing
and exporting data) and create workfile objects. These commands are listed in
Chapter 17. “Command Reference,” beginning on page 357.
• Object commands execute views and procedures on objects in the workfile (such as
series, groups and equations).
For example, unit root tests are done via a series command (series.uroot), co-inte-
gration tests are a group command (group.coint), and regression and forecasting
are performed via equation commands (equation.ls and equation.forecast).
The full set of object commands can be found in Chapter 1. “Object View and Proce-
dure Reference,” beginning on page 3, where they are listed by object type.
• Functions may be used to create new data, either in the form of workfile objects or as
program variables.
Creating a new series that is equal to the moving average of an existing series is done
with the @movav function. The @rbinom function is used to generate a random scalar
or series from the binomial distribution. @pagefreq may be used to generate a string
object or program variable containing the frequency of the current workfile page. In
general, functions all start with the @ symbol.
Documentation for @-functions available can be found in Chapter 18. “Function Ref-
erence,” on page 679, with topical summary listings provided in Chapter 14. “String
142—Chapter 6.Simple Programs

and Date Summary,” on page 331, Chapter 15. “Matrix Language Summary,” on
page 335, and Chapter 16. “Programming Language Summary,” on page 343
• Object data members allow you to retrieve a fundamental piece of data from an
object. Unlike object commands that execute a view or procedure on an object, data
members merely provide access to existing results. Data members almost all start with
an @ symbol and can be accessed by typing the name of the object followed by a “.”
and the name of the data member.
For example, eq1.@coefs returns a vector containing the estimated coefficients from
the equation object EQ1. ser01.@last returns a string containing the date (or obser-
vation number) of the last non-NA value in the series SER01. The list of data members
available for each object is listed in the object’s section of Chapter 1. “Object View
and Procedure Reference,” on page 3.

Let’s examine a simple example (the data series are provided in the database PROGDEMO in
your EViews directory so that you can try out the program). Create a new program by typing
program myprog

in the command window. In the program window that opens for MYPROG, we are going to
enter the commands to create a workfile, fetch a series from an EViews database named
PROGDEMO, run a regression, compute residuals and a forecast, make a plot of the forecast,
and save the results.
' housing analysis
wfcreate(wf=myhouse) m 1968m3 1997m6
fetch progdemo::hsf
smpl 1968m5 1992m12
equation reg1.ls hsf c hsf(-1)
reg1.makeresid hsfres
smpl 1993m1 1997m6
reg1.forecast hsffit
freeze(hsfplot) hsffit.line
save

The first line of the program is a comment, as denoted by the apostrophe “'”. In executing a
program, EViews will ignore all text following the apostrophe until the end of the line.

The line containing the wfcreate command creates a new workfile, called MYHOUSE, with
a monthly frequency spanning the dates March 1968 to June 1997. A series called HSF (total
housing units started) is fetched from the database PROGDEMO. The rest of the program
results in a saved workfile named MYHOUSE containing the HSF series, an equation object
REG1, residual and forecast series HSFRES and HSFFIT, and a graph HSFPLOT of the fore-
casts.
Program Variables—143

You can run this program by clicking on Run and filling in the dialog box.

Now, suppose you wish to perform the same analysis, but for the S&P 500 stock price index
(FSPCOM). Edit the program, changing MYHOUSE to MYSP500, and change all of the refer-
ences of HSF to FSPCOM:
' s&p analysis
wfcreate(wf=mysp500) m 1968m3 1997m6
fetch progdemo::fspcom
smpl 1968m5 1992m12
equation reg1.ls fspcom c fspcom(-1)
reg1.makeresid fspcomres
smpl 1993m1 1997m6
reg1.forecast fspcomfit
freeze(fscomplot) fspcomfit.line
save

Click on Run to execute the new analysis. Click on the Save button to save your program file
as MYPROG.PRG in the EViews directory.

Since these two programs are almost identical, it seems inefficient to have two separate pro-
grams for performing the analysis. In “Program Arguments” on page 155 we describe a
method for performing these two forecasting problems using a single program. First how-
ever, we must define the notion of program variables that exist solely when running pro-
grams.

Program Variables
While you can use programs just to run, and re-run collections of EViews commands, the
real power of the EViews programming language comes from the use of program variables
and program control statements.

Program variables are variables that you may use in place of numeric or string values in
your EViews programs. Accordingly, there are two basic types of program variables: control
(numeric) variables and string variables.

In the remainder of this section we describe the use of these two types of program variables.

Control Variables
Control variables are program variables that you can use in place of numeric 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.
144—Chapter 6.Program Variables

It is important to note that control variables do not exist outside of your program and are
automatically deleted after a program finishes. In this regard, control variables should not be
confused with scalar objects as the former 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.

The name of a control variable starts with an “!” character. After the “!”, the name should
be a legal EViews name of 23 characters or fewer (leading numbers are allowed). Examples
of control variable names are:
!x
!1
!counter

You need not declare control variables, but you must assign them values before use. Control
variable values 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. For example:
!x = 7
!12345 = 0
!counter = 12
!pi = 3.14159

Once assigned a value, a control variable may appear in an expression. For example:
!counter = !counter + 1
genr dnorm = 1/sqr(2*!pi)*exp(-1/2*epsilon^2)
scalar stdx = x/sqr(!varx)
smpl 1950q1+!i 1960q4+!i

For example, the following commands:


scalar stdx = sqr(!varx)
c(100) = !length
sample years 1960+!z 1990

use the numeric values assigned to the control variables !VARX, !LENGTH, and !Z.

It is important to note that control variables are used in programs via text substitution.
Whenever EViews encounters a control variable in a program it substitutes the text value of
that variable into the program. One of the implications of the text substitution is that you
may lose some numeric accuracy when using a program variable due to the conversion in to
and out of a text representation of the number.

A second unintended consequence of text substitution can arise when raising a negative
control variable to a power:
!a = -3
Program Variables—145

!b = !a^2

When evaluating these lines, EViews will substitute the value of !A in the second line, leav-
ing the line:
!b = -3^2

Which it then evaluates as –9 (since the square operator takes precedence over the negation
operator), rather than the expected 9.

You should also take care to avoid inadvertent replacement of program variables, as outlined
in “Replacement Variables” on page 147.

String Variables
A string expression or string is text enclosed in double quotes:
"gross domestic product"
"3.14159"
"ar(1) ar(2) ma(1) ma(2)"

A string program variable is a program variable whose value is a string of text. String vari-
ables, which exist only during the time that your program is executing, have names that
begin with a “%” symbol. String variables should not be confused with “String Objects” on
page 101 which are objects that exist in a workfile.

String variables are assigned by putting the string variable name on the left of an “=” sign
and a string expression on the right. For example, the following lines assign values to string
variables:
%value = "value in millions of u.s. dollars"
%armas = "ar(1) ar(2) ma(1) ma(2)"
%mysample = " 83m1 96m12"
%dep = " hs"
%pi = " 3.14159"

You may use strings variables to help you build up command text, variable names, or other
string values. EViews provides a number of operators and functions for manipulating
strings; a complete list is provided in “Strings” on page 85.

Once assigned a value, a string variable may appear in any expression in place of the under-
lying string. When substituted for, the string variable will be replaced by the contents of the
string variable, enclosed in double quotes.

Here is a simple example where we use string operations to concatenate the contents of
three string variables.
!repeat = 500
%st1 = " draws from the normal"
146—Chapter 6.Program Variables

%st2 = "Cauchy "


%st3 = @str(!repeat) + @left(%st1,16) + %st2 + "distribution"

In this example %ST3 is set to the value “500 draws from the Cauchy distribution”. Note the
spaces before “draws” and after “Cauchy” in the string variable assignments. After string
variable substitution, the latter assignment is equivalent to entering
%st3 = "500" + " draws from the " + "Cauchy " + "distribution"

Similarly, the table assignment statement


table1(1,1) = %st3

is equivalent to entering the command


table(1,1) = "500 draws from the Cauchy distribution"

One important use for string variables is assigning string values to string objects, string vec-
tors, or Alpha series. For example, we may have the assignment statement
%z = "Ralph"
alpha full_name = %z + last_name

which is equivalent to the expression


alpha full_name = "Ralph" + last_name

We again emphasize that string variable substitution involves replacing the string variable
by its string value contents, enclosed in double quotes.

As with any string value, you may convert a string variable containing the text representa-
tion of a number into a number by using the @val function. For example,
%str = ".05"
!level = @val(%str)

creates a control variable !LEVEL=0.05. If the string cannot be evaluated to a number, @val
returns the value “NA”.

String variables are closely related to the concept of a string object (“String Objects,” on
page 101). A string object is an EViews workfile object that holds a string:
string a = "Hello World"
string b = """First Name"" Middle ""Last Name"""

Unlike string variables, string objects are named objects in the workfile that may exist apart
from a running program.

In programming applications, string variables and string objects are sometimes defined
using string literal expressions as illustrated above. However, in most settings, string vari-
ables and objects are defined using results from string functions, or by manipulation of
string lists and string vectors. For example, you could use the @wlookup and @wsplit func-
Program Variables—147

tions to obtain a set of strings corresponding to the names of all of the series in a workfile.
See “Strings,” on page 85 for a full discussion.

Replacement Variables
When working with EViews commands, you may wish to use a string variable, not simply to
refer to a string value, but as an indirect way of referring to something else, perhaps a com-
mand, or an object name, or portion of names for one or more items.

Suppose, for example, that we assign the string variable %X the value “GDP”:
%x = "gdp"

We may be interested, however, not in the actual string variable value “gdp”, but rather in
an EViews object named “GDP”. Accordingly, we require a method of distinguishing between
a string value and the item corresponding to the string value.

If you enclose a string variable in curly braces (“{ ” and “}”) EViews will replace the expres-
sion with the name, names, or name fragment given by the string value. In this context we
refer to the expression “{%X}” as a replacement variable since the string variable %X is
replaced in the command line by the name or names of objects to which the string refers.

Suppose we want to create the series Y and set it equal to the values in the series GDP.
Given the string variable %X defined above, the series declaration,
series y = %x

creates a numeric series Y and sets it equal to the string value “gdp”,
series y = "gdp"

which generates an error since the series declaration expects the name of a series or a
numeric value, not a string value. In this circumstance, we would like to replace the string
value with the name of an object. With the replacement variable “{%X}”, the command
series y = {%x}

is properly interpreted as
series y = gdp

Similarly, the program line using replacement variables,


equation eq1.ls {%x} c {%x}(-1)

would be interpreted by EViews as


equation eq1.ls gdp c gdp(-1)

Changing the contents of %X to “M1” changes the interpretation of the original program line
to
equation eq1.ls m1 c m1(-1)
148—Chapter 6.Program Variables

since the replacement variable uses the name obtained from the new value of %X.

To take another example, when trying to find the number of valid (non-missing) observa-
tions in a series named INCOME, you may use the @obs function along with the name of the
series:
@obs(income)

If you wish to use a string variable %VAR to refer to the INCOME series, you must use the
replacement variable in the @obs function, as in
%var = "income"
@obs({%var})

since you wish to refer indirectly to the object named in %VAR. Note that the expression
@obs(%var)

will return an error since @obs requires a series or matrix object name as an argument.

Any string variable may be used as the basis of a replacement variable. Simply form your
string using one or more string operations
%object = "group"
%space = " "
%reg1 = "gender"
%reg2 = "income"
%reg3 = "age"
%regs = %reg1 + %space + %reg2 + %space + %reg3

then enclose the string variable in braces. In the expression,


{%object} g1 {%regs}

EViews will substitute the names found in %OBJECT and %REGS so that the resulting com-
mand is
group g1 gender income age

It is worth noting that replacement variables may be used as building blocks to form object
names. For example, the commands
%b = "2"
%c = "temp"
series z{%b}
matrix(2, 2) x{%b}
vector(3) x_{%c}_y

declare a series named Z2, a 2  2 matrix named X2, and a vector named X_TEMP_Y.
Program Variables—149

Up to this point, we have focused on replacement variables formed from string variables.
However, control variables may also be used to form replacement variables. For example,
the commands
!i = 1
series y{!i} = nrnd
!j = 0
series y{!j}{!i} = nrnd

are equivalent to
series y1 = nrnd
series y01 = nrnd

and will create two series Y1 and Y01 that contain a set of (pseudo-)random draws from a
standard normal distribution. Conveniently, in cases where there is no possibility of ambigu-
ity, EViews will treat a control variable as a replacement variable, even if the braces are not
provided. For example:
!x = 3
series y!x = 4

will generate the series Y3 containing the value 4.

While convenient, this loose interpretation of control variables can, however, lead to unex-
pected results if one is not careful. Take the following program:
!x1 = 10
series y = !x1

This program will create a series equal to the value of !X1 (i.e. 10). However if you were to
mis-type the program slightly:
!x = 10
series y = !x1

where the first line has !X rather than !X1, EViews will not generate an error due to the
missing !X1 variable, but will instead evaluate the second line by substituting !X into the
expression, and evaluating the result as 101.

Replacement variables may be constructed using nested evaluation of replacement variables.


Suppose we have the strings:
%str1 = "x"
%name = "%str1"

Then we can declare the series X and fill it with random normals using the command
series {{%name}} = nrnd

After evaluation of the innermost replacement variable, the expression reduces to


150—Chapter 6.Program Variables

series {%str1} = nrnd

and then to
series x = nrnd

when we evaluate the remaining brace. The double braces allow us perform a double
replacement in which the string variable used to form a replacement variable is itself
obtained as a replacement variable.

The double nested braces need not be adjacent. For example:


%x1 = "x"
%x2 = "y"
scalar x = 10
scalar y = 20
!y = 1
scalar r1 = {%x{!y}}
!y = 2
scalar r2 = {%x{!y}}

First we create two string variables, %X1 and %X2, and three scalar objects, X, Y, and R.
First, the control variable is !Y is set to 1 and the replacement variable {!Y} is used to con-
struct the name “%X1” of a string variable. The resulting replacement variable {%X1} refers
to the scalar object X. We assign the scalar X value of 10 to the scalar R1. Next, we set !Y to
2, the replacement variable {%X{!Y}} evaluates to Y, and we assign the Y value of 20 to the
scalar R2.

Multiple sets of braces may be used to create various string names:


string uslabel = "USA"
string nzlabel = "New Zealand"
%a1 = "US"
%a2 = "NZ"
%b = "LABEL"
!y = 1
string label1 = {%a{!y}}{%b}
!y = 2
string label2 = {%a{!y}}{%b}

First we create two string objects, USLABEL and NZLABEL, which hold the label we wish to
assign to each country. Then we create the string variables %A1 and %A2 to hold the coun-
try abbreviations. When the control variable !Y=1, {%A{!Y}}{%B} evaluates to the object
USLABEL and when !Y=2, {%A{!Y}}{%B} evaluates to the object NZLABEL. Then the
string LABEL1 contains “USA” and LABEL2 contains “New Zealand”.
Program Modes—151

Replacement variables may also be formed using string objects in place of string variables.
To use a string object as a replacement variable, simply surround it with curly braces (“{”
and “}”). For example,
string LAGGDP = "GDP(-1) GDP(-2) GDP(-4)"
equation eq1.ls GDP C {LAGGDP}

executes the command


equation eq1.ls GDP C GDP(-1) GDP(-2) GDP(-4)

In most respects, there is no difference between using a string object or a string variable in a
program. String objects have the advantage that they may be used interactively, outside of
programs, while string variables may not. This can be useful when debugging a program;
string variables disappear once the program has finished, making it difficult to identify prob-
lems in their construction. Note that string objects do, however, go out-of-scope when the
active workfile page changes, while string variables are always in scope.

Lastly, while replacement variables provide you with great flexibility in referencing objects
in your programs, used carelessly, they can lead to confusion. We suggest, for example, that
you avoid using similar base names to refer to different objects. Consider the following pro-
gram:
' possibly confusing commands (avoid)
!a = 1
series x{!a}
!a = 2
matrix x{!a}

In this code snippet, it is easy to see that X1 is the series and X2 is the matrix. But in a more
complicated program, where the control variable assignment !A=1 may be separated from
the declaration by many program lines, it may be difficult to tell at a glance what kind of
object X1 represents. A better approach might be to use different names for different kinds
of variables:
!a = 1
series ser{!a}
!a = 2
matrix mat{!a}

so that the meaning of replacement variable names are more apparent from casual examina-
tion of the program.

Program Modes
Program modes describe different settings associated with the execution of your program.
You may, for example, choose to provide verbose messaging where your program will echo
152—Chapter 6.Program Modes

each command to the status line, or you may choose quiet mode. Alternately, you may wish
to run a legacy program file in Version 4 compatibility mode.

EViews provides you with the opportunity to set program execution modes at the time that
the program is first run. In addition, you may use the “MODE” statement to change the exe-
cution mode of a program from within the program itself. One important benefit to using
“MODE” statements is that the program can begin executing in one mode, and switch to a
second mode as the program executes.

To change the mode for quiet or verbose mode, simply add a line to your program reading
“MODE” followed by either the “QUIET” or the “VERBOSE” keyword, as in
mode quiet

For version 4 compatibility, you should use the keyword “VER4”:


mode ver4

as a line in the body of the program.

Multiple settings may be set in a single “MODE” line:


mode quiet ver4

and multiple mode statements may be specified in a program to change the mode as the pro-
gram runs:
mode quiet
[some program lines]
mode verbose
[additional program lines]
Note that setting the execution mode explicitly in a program overrides any settings specified
at the time the program is executed.

Program Message Logging


When executing a program in EViews, it may be useful to keep track of what is happening
during execution. Log windows allow you to determine more accurately the state of various
objects in your workfile or follow program progression.
Program Modes—153

Log windows may be switched on using the logmode command.


The logmode command gives the ability to specify the name of the
log window and directs the messages to the window with the speci-
fied name. If no name is specified the messages are directed to a
window with the name of the program. If a program is executed
more than once and a log window has already been created, with no
name specified for the log, the log window will be cleared and all
subsequent messages will be sent to the existing log window. If you
wish to preserve a log, you may either select to append message,
save the log to a text file, or freeze it, which creates a text file object.
All of these actions can be accessed by the popup menu that appears
when right-clicking on a message log window.

The log windows appear as tabbed windows and can be rearranged


by the user. The logmode command has an option to have the log
window floating next to the program window.

There are several types of messages that can be logged: program lines, status line messages,
user log messages, and program errors. When displayed in a log message, each type will
appear in a different color, making it easier to differentiate one type from another. Program
lines are echoes of the line of code in the program currently being executed, and are dis-
played in black. Status line messages are the messages displayed in the status line and
154—Chapter 6.Program Modes

appear in blue. User log messages are custom messages created by the program via the
logmsg command and appear in green. Program errors are messages generated when a log-
ical or syntax error has occurred and appear in red.

Beginning with EViews 14, all program log windows appear as tabbed windows and may be
rearranged. Additionally, you have the ability to specify a name for the log window and
direct the messages to the log window with the specified name. If no name is specified, the
messages are directed to a window with the name of the program. This was the default
behavior in versions of EViews before EViews 10.

Logging Options
The Message settings dialog in the Programs section of the General Options dialog specifies
whether EViews runs programs in Verbose mode (the default), lists commands in the status
line as they are executed, or uses Quiet mode, which suppresses this information. EViews
will run faster in quiet mode since the status line display does not need to be updated.

This default may always be overridden from the Run Program dialog, or by using the option
"q" in the run statement, as in:
run(q) myprogram

In addition, you may modify the Logging settings to delete (Clear) or leave (Append) the
contents of the log window on program start.

See also the logmode (p. 506), logmsg (p. 509), logclose (p. 505), and logsave (p. 509)
commands, which all have additional options to specify the name of the log.
Program Arguments—155

Program Arguments
Program arguments are special string variables that are passed to your 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 appropri-
ate. Any number of arguments may be included in a program. The individual arguments will
be available in the string variables “%0”, “%1”, “%2”, and so on; the “%ARGS” variable
will contain a space delimited list of all the arguments passed into the program.

When you run a program that takes arguments, you may supply the values for the argu-
ments. 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 or exec command, you may list the argu-
ments consecutively after the name of the program.

For example, suppose we have a program named “REGPROG”:


equation eq1
smpl 1980q3 1994q1
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 command:
eq1.ls lgdp c m1 m1(-1) time

Alternatively, you can run this program by clicking on the Run button on the program win-
dow, or selecting File/Run.... In the Run Program dialog box that appears, type the name of
the program in the Program name or path field and enter the values of the arguments in
the Program arguments field. For this example, type “regprog” for the name of the program,
and “lgdp” and “m1” for the arguments.

Any arguments in your program that are not initialized in the Run Program dialog or run
command are treated as empty string variables. For example, suppose you have a one-line
program named “REGRESS”:
equation eq1.ls y c time {%0} {%1} {%2} {%3} {%4} {%5} {%6} {%7}
{%8}

The command,
exec regress x x(-1) x(-2)

executes
equation eq1.ls y c time x x(-1) x(-2)

while the command,


156—Chapter 6.Program Options

exec regress

executes
ls y c time

In both cases, EViews ignores arguments that are not included in your run command.

As a last example, we repeat our simple forecasting program from above, but use arguments
to simplify our work. Suppose you have the program “MYPROG”:
wfcreate(wf={%0}) m 1968m3 1997m6
fetch progdemo::{%1}
smpl 1968m5 1992m12
equation reg1.ls {%1} c {%1}(-1)
reg1.makeresid {%1}res
smpl 1993m1 1997m6
reg1.forecast {%1}fit
freeze({%1}plot) {%1}fit.line
save

The results of running the two example programs at the start of this chapter can be dupli-
cated by executing MYPROG with arguments:
exec myprog myhouse hsf

and
exec myprog mysp500 fspcom

Program Options
Much like program arguments, program options are special string variables that may be
passed to your program when you run the program. You may specify options by providing a
comma separated list of options in parentheses in the run or exec command statement,
immediately after the name of the program as in:
run myprogram(myoption1, myoption2)

Note that options are only supported via the command line method using run or exec. You
cannot pass an option to a program when running a program via the menus. Options are
included via the command line by entering them in parenthesis immediately following the
name of the program to be run.

In contrast with arguments, options may not be accessed directly from within your program.
Rather you can only test for the existence of an option, or retrieve part of an option. The
@hasoption command lets you test for the existence of an option. For example, @hasop-
tion("k") will return a value of 1 if the “k” option was passed into the program at run
time, or 0 if it was not.
Control of Execution—157

@equaloption may be used to return the value to the right of an equality sign in an option.
For example if “cov=hac” is entered as an option, @equaloption("cov") would return
“hac”. If the option was not entered at all, @equaloption will return an empty string.

For example, suppose you have the following program:


%filename = @equaloption("file")
wfcreate(wf={%filename}) m 1968m3 1997m6
fetch progdemo::{%0}
if (@hasoption("LS")=1) then
smpl 1968m5 1992m12
equation reg1.ls {%0} c {%0}(-1)
endif

If you were to run this program with:


run myprog(file=myhouse, ls) hsf

the program would create a workfile called MYHOUSE, would fetch a series called HSF, and
would then create an equation called REG1 by performing least squares using the series HSF
(for discussion of the “if” condition used in this example, see “IF Statements” on page 157).

If we had run the program with just:


run myprog hsf

the workfile would not have been named (and would be given the default name of UNTI-
TLED), and the regression would not have been run.

Note that if your program name has spaces or illegal characters, it must be enclosed within
quotes in run or exec commands. In this case, program options should be included after
the closing quote without a space. For example, if we were to name our above program as
MY PROG, then the correct method to issue options is:
run "my prog"(file=myhouse, ls) hsf

Control of Execution
EViews provides you with several ways to control the execution of commands in your pro-
grams. Controlling execution in your program means that you can execute commands selec-
tively or repeatedly under changing conditions. The tools for controlling execution will be
familiar from other computer languages.

IF Statements
There are situations where you may want to execute commands only if some condition is
satisfied. EViews uses IF and ENDIF, or IF, ELSE, and ENDIF statements to indicate the con-
dition to be met and the commands to be executed.
158—Chapter 6.Control of Execution

An IF statement starts with the if keyword, followed by an expression for the condition,
and then the word then. You may use AND/OR statements in the condition, using parenthe-
ses to group parts of the statement as necessary.

All comparisons in the IF statement follow the rules outlined in “String Relational Opera-
tors” on page 87 and in “Numeric Relational Operators” on page 198 of User’s Guide I. Note
in particular that string comparisons are case-sensitive. You may perform caseless compari-
son using the @upper or @lower string functions as in
if (@lower(%x) = "abc") then

or
if (@upper(%x) = "ABC") then

If the expression is true, all of the commands until the matching endif are executed. If the
expression is false, all of these commands are skipped. For example,
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 1950q1 1970q1+!a
endif

only generates the series GNPSTD and CONSTD and sets the sample if the corresponding IF
statements are true. Note that we have indented the lines between the if and the endif state-
ments. The indentation is added for program clarity and has no effect on the execution of
the program lines.

The expression to be tested may also take a numerical value. In this case, 0 and NA are
equivalent to false and any other non-zero value evaluates to true. For example,
if !scale then
series newage = age/!scale
endif

executes the series statement if !SCALE is a non-missing, non-zero value.

An IF statement may include a matching ELSE clause containing commands to be executed


if the condition is FALSE. If the condition is true, all of the commands up to the keyword
else will be executed. If the condition is FALSE, all of the commands between else and
endif will be executed. For example:
if !scale>0 then
series newage = age/!scale
Control of Execution—159

else
series newage = age
endif

It is worth noting that this example performs a conditional recode in which the series NEW-
AGE is assigned using one expression if a condition is true, and a different expression other-
wise. EViews provides a built-in @recode function for performing this type of evaluation;
see @recode (p. 1068).

IF statements may also be applied to string variables:


if %0="CA" or %0="IN" then
series stateid = 1
else
if %0="MA" then
series stateid=2
else
if %0="IN" then
series stateid=3
endif
endif
endif

Note that the nesting of our comparisons does not cause any difficulties.

You should note when using the IF statement with series or matrix objects that the compari-
son is defined on the entire object and will evaluate to false unless every element of the ele-
ment-wise comparison is true. Thus, if X and Y are series, the IF statement
if x<>y then
[some program lines]
endif

evaluates to false if any element of X does not equal the corresponding value of Y in the
default sample. If X and Y are identically sized vectors or matrices, the comparison is over
each of the elements X and Y. This element-wise comparison is described in greater detail in
“Relational Operators (=, >, >=, <, <=, <>)” on page 296.

If you wish to operate on individual elements of a series on the basis of element-wise condi-
tions, you should use the @recode function or use smpl statements to set the observations
you wish to change. Element-wise operations on a vector or matrix should use comparisons
of individual element comparisons
160—Chapter 6.Control of Execution

if x(3)=7 then
x(3) = 2
endif

or the element-wise matrix functions (“Matrix Element” on page 340).

The FOR Loop


The FOR loop allows you to repeat a set of commands for different values of numerical or
string variables. The FOR loop begins with a for statement and ends with a next state-
ment. Any number of commands may appear between these two statements.

The syntax of the FOR statement differs depending upon whether it uses numerical variables
or string variables.

FOR Loops with Numerical Control Variables or Scalars


To repeat statements for different values of a control variable, you should follow the for key-
word by a control variable initialization, the word to, and then an ending value. After the
ending value you may include the word step followed by a number indicating an amount to
change the control variable each time the loop is executed. If you don’t include step, the
step is assumed to be 1. Consider, for example the loop:
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.

We may add the step keyword and value to the FOR loop to modify the step:
for !j=10 to 1 step -1
series rescale{!j}=original/!j
next

In this example, the step is -1, and !J is used as a replacement variable in naming the ten
constructed series RESCALE10 through RESCALE1 and as a control variable scalar divisor in
the series ORIGINAL.

The commands inside the FOR loop are first executed for the initial control value (unless
that value is already beyond the terminal value). After the initial execution, the control vari-
able is incremented by step and EViews compares the new control variable value to the
limit. If the limit is exceeded, execution stops.
Control of Execution—161

One important use of FOR loops with control variables is to change the workfile sample
using a smpl command. If you add a control variable to a date in a smpl command state-
ment, you will get a new date as many observations forward as the current value of the con-
trol variable. Here is a FOR loop that gradually increases the size of the sample and
estimates a recursive regression:
for !horizon=10 to 72
smpl 1970m1 1970m1+!horizon
equation eq{!horizon}.ls sales c orders
next

One other important case uses loops and control variables to access elements of a matrix
object. For example,
!rows = @rows(vec1)
vector cumsum1 = vec1
for !i=2 to !rows
cumsum1(!i) = cumsum1(!i-1) + vec1(!i)
next

computes the cumulative sum of the elements in the vector VEC1 and saves it in the vector
CUMSUM1.

To access an individual element of a series, you will need to use the @elem function and
@otod to get the desired element
for !i=2 to !rows
cumsum1(!i) = @elem(ser1, @otod(!i))
next

The @otod function returns the date associated with the observation index (counting from
the beginning of the workfile), and the @elem function extracts the series element associ-
ated with a given date.

You may nest FOR loops to contain loops within loops. The entire inner FOR loop is exe-
cuted for each successive value of the outer FOR loop. For example:
matrix(25,10) xx
for !i=1 to 25
for !j=1 to 10
xx(!i,!j)=(!i-1)*10+!j
next
next
162—Chapter 6.Control of Execution

You should avoid changing the control variable within a FOR loop. Consider, for example,
the commands:
' potentially confusing loop (avoid doing this)
for !i=1 to 25
vector a!i
!i=!i+10
next

Here, both the FOR assignment and the assignment statement within the loop change the
value of the control variable !I. Loops of this type are difficult to follow and may produce
unintended results. If you find a specific need to change a control variable inside the loop,
you should consider using a WHILE loop (“The WHILE Loop” on page 164) as an alterna-
tive to the FOR loop.

You may execute FOR loops with scalars instead of control variables. However, you must
first declare the scalar, and you may not use the scalar as a replacement variable. For exam-
ple,
scalar i
scalar sum = 0
vector (10) x
for i=1 to 10
x(i) = i
sum = sum + i
next

In this example, the scalar objects I and SUM remain in the workfile after the program has
finished running, unless they are explicitly deleted. When using scalar objects as the looping
variable you should be careful that the scalar is always available white the FOR loop is
active. You should not, for example, delete the scalar or change the workfile page within the
FOR loop.

FOR Loops with String Variables and String Objects


To repeat statements for different values of a string variable, you may use the FOR loop to let
a string variable range over a list of string values. You should list the FOR keyword, followed
by the name of the string program variable, followed by the list of values. For example,
for %y gdp gnp ndp nnp
equation {%y}trend.ls {%y} c {%y}(-1) time
next

executes the commands


Control of Execution—163

equation gdptrend.ls gdp c gdp(-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 may include multiple string variables in the same FOR statement—EViews will process
the string values in sets. For example, we may define a loop with list three string variables:
for %1 %2 %3 1955q1 1960q4 early 1970q2 1980q3 mid 1975q4 1995q1
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:
smpl 1955q1 1960q4
equation earlyeq.ls sales c orders
smpl 1970q2 1980q3
equation mideq.ls sales c orders
smpl 1975q4 1995q1
equation lateeq.ls sales c orders

Both string objects and replacement variables may be used to specify a list for use in loops,
by surrounding the object name or replacement variable with curly braces (“{ }”). For
example,
string dates = "1960m1 1960m12"
%label = "year1"
for %1 %2 %3 {dates} {%label}
smpl {%1} {%2}
equation {%3}eq.ls sales c orders
next

finds the three strings for the loop by taking two elements of the string list and one element
of the string variable:
smpl 1960m1 1960m12
equation year1eq.ls sales c orders

Note the difference between using a FOR loop with multiple string variables and using
nested FOR loops. In the multiple string variable case, all string variables are advanced at
the same time, while with nested loops, the inner variable is advanced over all choices, for
each value of the outer variable. For example:
164—Chapter 6.Control of Execution

!eqno = 1
for %1 1955q1 1960q4
for %2 1970q2 1980q3 1975q4
smpl %1 %2
'form equation name as eq1 through eq6
equation eq{!eqno}.ls sales c orders
!eqno=!eqno+1
next
next

Here, the equations are estimated over the samples 1955Q1–1970Q2 for EQ1, 1955Q1–
1980Q3 for EQ2, 1955Q1–1975Q4 for EQ3, 1960Q4–1970Q2 for EQ4, 1960Q4–1980Q3 for
EQ5, and 1960Q4–1975Q4 for EQ6.

Note that you may use the exitloop command to exit a FOR loop early. See “Exiting
Loops” on page 166.

The WHILE Loop


In some cases, we wish to repeat a series of commands several times, but only while one or
more conditions are satisfied. Like the FOR loop, the WHILE loop allows you to repeat com-
mands, but the WHILE loop provides greater flexibility in specifying the required conditions.

The WHILE loop begins with a while statement and ends with a wend statement. Any num-
ber of commands may appear between the two statements. WHILE loops can be nested.

The WHILE statement consists of the while keyword followed by an expression involving a
control variable or scalar object. 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 consid-
ered true.

If the expression is true, the subsequent statements, up to the matching wend, will be exe-
cuted, and then the procedure is repeated. If the condition is false, EViews will skip the fol-
lowing commands and continue on with the rest of the program following the wend
statement. For example:
!val = 1
!a = 1
while !val<10000 and !a<10
smpl 1950q1 1970q1+!a
series inc{!val} = income/!val
!val = !val*10
Control of Execution—165

!a = !a+1
wend

There are four parts to this WHILE loop. The first part is the initialization of the control vari-
ables used in the test condition. The second part is the WHILE statement which includes the
test. The third part is the statements updating the control variables. Finally the end of the
loop is marked by the word wend.

Unlike a FOR statement, the WHILE statement does not update the control variable used in
the test condition. You need to include an explicit statement inside the loop to change the
control variable, or your loop will never terminate. Use the F1 key to break out of a program
which is in an infinite loop.

Earlier, we cautioned against this behavior creating FOR loops that explicitly change the
control variable inside the loop and offered an example to show the resulting lack of clarity
(p. 162). Note that the equivalent WHILE loop provides a much clearer program:
!i = 1
while !i<=25
vector a{!i}
!i = !i + 11
wend

Note that you may use the exitloop command to exit a WHILE loop early. See “Exiting
Loops” on page 166.

Execution Errors
By default, EViews will stop executing after encountering any errors. You can instruct the
program to continue running even if errors are encountered by changing the maximum error
count from the Run dialog (see “Executing a Program” on page 133), or by using the set-
maxerrs (p. 588) command inside a program.

Handling Errors
You may wish to perform different tasks when errors are encountered. For example, you may
wish to skip a set of lines which accumulate estimation results when the estimation proce-
dure generated errors, or you may wish to overwrite the default EViews error with one of
your own, using the seterr (p. 587) command.

EViews offers a number of different ways to test for and handle execution errors. For exam-
ple, the @lasterrstr (p. 942) command will return a string containing the previous line's
error. If the previous line of your program did not error, this string will be empty. Alterna-
tively you could use the @errorcount (p. 877) function to check the number of errors cur-
rently encountered before and after a program line has been executed.
166—Chapter 6.Control of Execution

For example, to test whether the estimation of an equation generated an error, you can com-
pare the number of errors before and after the command:
!old_count = @errorcount
equation eq1.ls y x c
!new_count = @errorcount
if !new_count > !old_count then
[various commands]
endif

Here, we perform a set of commands only if the estimation of equation EQ1 incremented the
error count.

For additional error handling functions, see “Support Commands” on page 343 and “Sup-
port Functions” on page 345.

Stopping Programs
Occasionally, you may want to stop a program based on some conditions. To stop a program
executing in EViews, use the stop command. For example, suppose you write a program
that requires the series SER1 to have nonnegative values. The following commands check
whether the series is nonnegative and halt the program if SER1 contains any negative value:
series test = (ser1<0)
if @sum(test) <> 0 then
stop
endif

Note that if SER1 contains missing values, the corresponding elements of TEST will also be
missing. But since the @sum function ignores missing values, the program does not halt for
SER1 that has missing values, as long as there is no negative value.

Exiting Loops
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.

As a simple example, suppose you computed a sequence of LR test statistics LR11, LR10,
LR9, ..., LR1, say to test the lag length of a VAR. The following program sequentially carries
out the LR test starting from LR11 and tells you the statistic that is first rejected at the 5%
level:
!df = 9
for !lag = 11 to 1 step -1
Multiple Program Files—167

!pval = 1 - @cchisq(lr{!lag},!df)
if !pval<=.05 then
exitloop
endif
next
scalar lag=!lag

Note that the scalar LAG has the value 0 if none of the test statistics are rejected.

If the exitloop is issued inside nested loops it will stop execution of the innermost loop.
Execution of the remaining loops is unaffected.

Multiple Program Files


When working with long programs, you may wish to organize your code using multiple
files. For example, suppose you have a program file named “Powers.PRG” which contains a
set of program lines that you wish to use.

While you may be tempted to string files together using the run command, we caution you
that EViews will stop after executing the commands in a run-referenced file. Thus, a pro-
gram containing the lines
run powers.prg
series x = nrnd

will only execute the commands in the file “Powers.PRG”, and will stop before generating
the series X. This behavior is probably not what you intended.

The exec command may be used execute commands in a file in place of the run command.
Though exec is quite similar to the run command, there are important differences between
the two commands:
• First, exec allows you to write general programs that execute other programs, some-
thing that is difficult to do using run, since the run command ends all program exe-
cution when processing of the named file is completed. In contrast, once exec
processing completes, the calling program will continue to run.
• Second, the default directory for exec is the Add-ins directory (in contrast with both
run and include which defaults to using the EViews default directory). Thus, the
command
exec myprog1.prg
will run the program file “Myprog1.prg” located in the default Add-ins directory. You
may specify files using relative paths in the standard fashion. The command:
exec MyAddIn\myprog2.prg
168—Chapter 6.Subroutines

runs the program “Myprog2.prg” located in the “MyAddIn” subdirectory of the Add-
ins directory.

If you wish to run a program that is located in the same directory as the calling program,
simply issue a “.\” at the start of the program name:
exec .\myprog2.prg

Alternatively you may use the include keyword to include the contents of a program file in
another program file. For example, you can place the line
include powers

at the top of any other program that needs to use the commands in POWERS. include also
accepts a full path to the program file, and you may have more than one include statement
in a program. For example, the lines,
include c:\programs\powers.prg
include durbin_h
[more lines]
will first execute all of the commands in “C:\Programs\Powers.PRG”, will execute the com-
mands in “Durbin_h.PRG”, and then will execute the remaining lines in the program file.

If you do not provide an absolute path for your include file, EViews will use the location of
the executing program file as the base location. In the example above, EViews will search for
the “Durbin_h.PRG” file in the directory containing the executing program.

Note that in contrast to using exec to execute another program, include simply inserts the
child program into the parent. This insertion is done prior to executing any lines in either
program. One important consequence of this behavior is that any program variables that are
declared in the parent program will not be available in the child/included program, even if
they are declared prior to the include statement.

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 may also use sub-
routines from one program to perform the same task in other programs.

Defining Subroutines
A subroutine begins with the keyword subroutine followed by the name of the routine and
any arguments, and ends with the keyword endsub. Any number of commands can appear
in between. The simplest type of subroutine has the following form:
subroutine z_square
series x = z^2
Subroutines—169

endsub

where the keyword subroutine is followed only by the name of the routine. This subrou-
tine 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 may 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.
The following program exits the subroutine if Durbin’s h statistic (Greene, 2008, p. 646, or
Davidson and MacKinnon, 1993, p. 360) for testing serial correlation with a lagged depen-
dent variable cannot be computed:
subroutine durbin_h
equation eqn.ls cs c cs(-1) inc
scalar test=1-eqn.@regobs*eqn.@cov(2,2)
' an error is indicated by test being nonpositive
' exit on error
if test<=0 then
return
endif
' compute h statistic if test positive
scalar h=(1-eqn.@dw/2)*sqr(eqn.@regobs/test)
endsub

Subroutine with Arguments


The subroutines we have seen thus far have been written to work with a specific set of vari-
ables. More generally, subroutines can take arguments. Arguments allow you to change the
behavior of the group of commands each time the subroutine is used. You may be familiar
with the concept from other programming languages, but if now, you are probably familiar
with similar concepts in mathematics. You can define a function, say
2
fx  x (6.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 0.7839, you can write f  0.7839  .
If you want to evaluate the function at a different value, say 0.50123, you merely write
f  0.50123  . By defining the function, you save yourself from writing the full function
expression every time you wish to evaluate it for a different value.

To define a subroutine with arguments, you start with the subroutine keyword, followed
by the subroutine name and (with no space) the arguments separated by commas, enclosed
170—Chapter 6.Subroutines

in parentheses. Each argument is specified by listing a type of EViews object, followed by


the name of the argument. For example:
subroutine power(series v, series y, scalar p)
v = y^p
endsub

This subroutine generalizes the example subroutine Z_SQUARE. Calling the subroutine
POWER will fill the series given by the argument V with the power P of the series specified
by the argument Y. So if you set V equal to X, Y equal to Z, and P equal to 2, you will get the
equivalent of the subroutine Z_SQUARE above. See the discussion below on how to call sub-
routines.

When creating subroutines with scalar or string arguments, you will define your arguments
using the scalar or the string types. Beyond that, you have a choice of whether you can
to make the corresponding argument a (temporary) program variable or a (permanent)
workfile object:
• To make the argument a program variable, you should use a program variable name
(beginning with a “!” for a control variable and a “%” for a string variable). If you
choose to use program variables, they should be referred to using the “!” or “%”
name inside the subroutine.
• To make the argument a workfile object, you should use a standard EViews object
name. The object should be referred to by the argument name inside the subroutine.

Obviously, you can mix the two approaches in the definition of any subroutine.

For example, the declaration


subroutine mysub(scalar !a, string %b)

uses program variable names, while


subroutine mysub(scalar a, string b)

uses object names. In the first case you should refer to “!A” and “%B” inside the subroutine;
in the latter case, you should refer to the objects named “A” and “B”.

If you define your subroutine using program variables, the subroutine will operate on them
as though they were any other program variable. The variables, which cannot go out-of-
scope, should be referred to using the “!” or “%” argument name inside the subroutine.

If you define your subroutine using object names, the subroutine will operate on those vari-
ables as though they were scalar or string objects. The variables, which may be deleted and
may go out-of-scope (if, for example, you change the workfile page), should be referred to
using the argument names as though they were scalar or string objects.

(We discuss in detail related issues in “Calling Subroutines,” beginning on page 171.)
Subroutines—171

You should note that EViews makes no distinction between input or output arguments in a
subroutine. Each argument may be an input to the subroutine, an output from the subrou-
tine, or both (or neither!). There is no way to declare that some arguments are inputs and
some are outputs. There is no need to order the arguments in any particular order. However
we find it much easier to read subroutine code when we stick to a convention, such as list-
ing all output arguments prior to all input arguments (or vice versa).

Calling Subroutines
Once a subroutine is defined, you may execute the commands in the subroutine by using the
call keyword. 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 (with
no space after the subroutine name). If the subroutine takes arguments, the arguments must
be provided in the same order as in the declaration statement. Here is an example program
file that calls subroutines:
include powers
load mywork
fetch z gdp
series x
series gdp2
series gdp3
call z_square
call power(gdp2,gdp,2)
call power(gdp3,gdp,3)

The call of the Z_SQUARE subroutine fills the series X with the value of Z squared. Next, the
call to the POWER subroutine creates the series GDP2 which is GDP squared. The last call to
POWER creates the series GDP3 as the cube of GDP.

When calling your subroutine, bear in mind that:


• When the subroutine argument is a scalar, the subroutine may be called with a scalar
object, a control variable, a simple number (such as “10” or “15.3”), a matrix element
(such as “mat1(1,2)”) or a scalar expression (such as “!y+25”).
• Subroutines with a string argument may be called with a string object, a string pro-
gram variable, simple text (such as “hello”) or an element of an svector object.
• Subroutines that take matrix and vector arguments can be called with a matrix name,
and if not modified by the subroutine, may also take a matrix expression.
• All other arguments must be passed to the subroutine with an object name referring
to a single object of the correct type.
172—Chapter 6.Subroutines

In “Subroutine with Arguments” on page 169 we described how you can define subroutines
that use either program variables or objects for scalar or string arguments. However you
define your subroutine, you may call the subroutine using either program variables or
objects—you are not required to match the calling arguments with the subroutine definition.
Suppose, for example, that you define your subroutine as
subroutine mysub(scalar a, string b)

Then for scalar and string objects F and G, and program variables !X and %Y,
scalar f = 3
string g = "hello"
!x = 2
%y = "goodbye"

you may call the subroutine using any of the following commands:
call mysub(!x, %y)
call mysub(!x, g)
call mysub(f, %y)
call mysub(f, g)

Note that changes to the scalars A and B inside the subroutine will change the correspond-
ing program variable or object that you pass into the routine.

Similarly, you may define


subroutine mysub(scalar !a, string !b)

and use the same four call statements to execute the subroutine commands.

However the subroutine is called, bear in mind that behavior inside the subroutine is depen-
dent on whether the subroutine declaration is in terms of program variables or objects, not
on the variable type that is passed into the subroutine.

Subroutine Placement
Subroutine definitions may be placed anywhere throughout your program. However, for
clarity, we recommend grouping subroutine definitions together either at the start or at the
end of your program. The subroutines will not be executed until they are executed by the
program using a call statement. For example:
subroutine z_square
series x=z^2
endsub
' start of program execution
load mywork
fetch z
Subroutines—173

call z_square

Execution of this program begins with the load statement; the subroutine definition is
skipped and is executed only at the last line when it is “called.”

Subroutine definitions must not overlap—after the subroutine keyword, there should be
an endsub before the next subroutine declaration. Subroutines may call each other, or
even call themselves.

Alternatively, you may place frequently used subroutines in a separate program file and use
an include statement to insert them at the beginning of your program. If, for example, you
put the subroutine lines in the file “Powers.PRG”, then you may put the line:
include powers

at the top of any other program that needs to call Z_SQUARE or POWER. You can use the
subroutines in these programs as though they were built-in parts of the EViews program-
ming language.

Global and Local Variables


Subroutines work with variables and objects that are either global or local.

Global variables refer either to objects which exist in the workfile when the subroutine is
called, and to objects that are created in the workfile by a subroutine. Global variables
remain in the workfile when the subroutine finishes.

A local variable is one that is defined within the subroutine. Local variables are deleted from
the workfile once a subroutine finishes. The program that calls the subroutine will not be
able to use a local variable since the local variable disappears once the subroutine finishes
and the original program continues.

Global Subroutines
By default, subroutines in EViews are global. 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:


• All objects created by a global subroutine are global and will remain in the workfile
when the subroutine finishes.
• Global objects may be used and updated directly from within the subroutine. If, how-
ever, a global object has the same name as an argument in a subroutine, the variable
name will refer to the argument and not to the global variable.
174—Chapter 6.Subroutines

• The global objects corresponding to arguments may be used and updated by referring
to the arguments.

Here is a simple program that calls a global subroutine:


subroutine z_square
series x = z^2
endsub
load mywork
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 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 argu-
ment name takes precedence so that any reference to the name in the subroutine will refer
to the argument, not to the global variable. For example:
subroutine sqseries(series z, string sername)
series {sername} = z^2
endsub
load mywork
fetch z
fetch y
call sqseries(y, "y2")

In this example, there is a series Z in the original workfile and Z is also an argument of the
subroutine. Calling SQSERIES with the argument set to Y tells EViews to use the series
passed-in via the argument Z instead of the global Z series. On completion of the routine,
the new series Y2 will contain the square of the series Y, not the square of the series Z. Since
keeping track of variables can become confusing when subroutine arguments take the same
name as existing workfile objects, we encourage you to name subroutine arguments as
clearly and distinctly as possible.

Global subroutines may call global subroutines. You should make certain to pass along
required arguments when you call a subroutine from within a subroutine. For example,
subroutine wgtols(series y, series wt)
equation eq1
call ols(eq1, y)
equation eq2
Subroutines—175

series temp = y/sqr(wt)


call ols(eq2, temp)
delete temp
endsub
subroutine ols(equation eq, series y)
eq.ls y c y(-1) y(-1)^2 y(-1)^3
endsub

can be run by the program:


load mywork
fetch cpi
fetch cs
call wgtols(cs,cpi)

In this example, the subroutine WGTOLS must explicitly pass along arguments to the sub-
routine OLS so that it uses the correct series and equation objects.

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 matrix X generates an error since X exists and is a series, but the declaration
of the matrix Y works (assuming there is no Y in the workfile MYWORK, or that Y exists and
is already a matrix):
subroutine newxy
matrix(2,2) x = 0
matrix(2,2) y = 0
endsub
load mywork
series x
call newxy

If you call this subroutine, EViews will return an error indicating that the global series X
already exists and is of a different type than a matrix.

Local Subroutines
If you include the word local in the definition of the subroutine, you create a local subrou-
tine. Local subroutines are most useful when you wish to write a subroutine which creates
many temporary objects that you do not want to keep.

The rules for variables in local subroutines are:


176—Chapter 6.Subroutines

• All objects created by a local subroutine will be local and will be removed from the
workfile upon exit from the subroutine.
• The global objects corresponding to subroutine arguments may be used and updated
in the subroutine by referring to the arguments.
• You may not use or update global objects that do not correspond to subroutine argu-
ments.

There is one exception to the general inaccessibility of non-argument global variables in


local subroutines. When a global group is passed as an argument to a local subroutine, all of
the series in the group are accessible to the local routine.

The last two rules deserve a bit of elaboration. In general, local subroutines do not have
access to any global variables unless those variables are associated with arguments passed
into the subroutine. Thus, if there is a series X in the workfile, a local subroutine will not be
allowed to use or modify X unless it is passed into the subroutine using a series argument.
Conversely, if X is passed into the subroutine, it may be modified.

Since locally created objects will vanish upon completion of the subroutine, to save results
from a local subroutine, you have to include them as arguments. For example, consider the
subroutine:
subroutine local ols_local(series y, series res, scalar ssr)
equation temp_eq.ls y c y(-1) y(-1)^2 y(-1)^3
temp_eq.makeresid res
ssr = temp_eq.@ssr
scalar se = ssr/temp_eq.@df
endsub

This local subroutine takes the series Y as input and modifies the argument series RES and
argument scalar SSR as output. Note that since Y, RES, and SSR are the only arguments of
this local subroutine, the only global variables that may be used or modified are those asso-
ciated with these arguments.The equation object TEMP_EQ and the scalar SE are local to the
subroutine and will vanish when the subroutine finishes.

Here is an example program that calls this local subroutine:


load mywork
fetch hsf
equation eq1.ls hsf c hsf(-1)
eq1.makeresid rres
scalar rssr = eq1.@ssr
series ures
scalar ussr
Subroutines—177

call ols_local(hsf, ures, ussr)

Note that we first declare the series URES and scalar USSR before calling the local subrou-
tine. These objects are global since they are declared outside the local subroutine. Since we
call the local subroutine by passing these global objects as arguments, the subroutine can
use and update these global variables.

Object commands that require access to global variables should be used with care in local
subroutines since that the lack of access to global variables can create problems for views or
procs of objects passed into the routine. For example, a subroutine of the form:
subroutine local bg(equation eq)
eq.hettest z c
endsub

will fail because the hettest equation proc requires access to the original variables in the
equation and the global variable Z, and these series are not available since they are not
passed in as arguments to the subroutine.

Care should also be taken when using samples and local subroutines. If the workfile sample
is based upon a series in the workfile (for example “smpl @all if x>0”), most procedures
inside the local subroutine will fail unless all of the series used in the sample are passed into
the subroutine.

Local Samples
Local samples in subroutines allow you to indicate that changes to the workfile sample are
temporary, with the original sample restored when you exit the routine. This feature is use-
ful when designing subroutines which require working on a subset of observations in the
original sample.

You may, in a subroutine, use the local smpl statement to indicate that subsequent
changes to the sample are temporary, and should be undone when exiting the subroutine.
The command
local smpl

makes a copy of the existing sample specification. You may then change the sample as many
times as desired using the smpl statement, and the original sample specification will be
reapplied when existing from the subroutine.

You may use the global smpl statement to indicate that subsequent smpl statements will
result in permanent changes to the workfile sample. Thus, the commands:
global smpl
smpl 5 100

in a subroutine permanently change the sample.


178—Chapter 6.User-Defined Dialogs

For example, consider the following program snippet which illustrates the behavior of local
and global samples:
workfile temp u 100
call foo
subroutine foo
smpl 2 100
local smpl
smpl 10 100
endsub

Here, we create a workfile with 100 observations and an initial workfile sample of “1 100”,
then call the subroutine FOO. Inside FOO, the first smpl statement changes the workfile
sample to “2 100”. We then issue the local smpl statement which backs up the existing
sample and identifies subsequent sample changes as local. The subsequent change to the
“10 100” sample is local so that when the subroutine exits, the sample is reset to “2 100”.

If instead we define FOO to be


subroutine foo
smpl 2 100
local smpl
smpl 10 100
global smpl
smpl 5 100
local smpl
smpl 50 100
endsub

As before, first smpl statement changes the workfile sample to “2 100” and the local smpl
statement and following smpl statement set the local sample to “10 100”. The global smpl
indicates that subsequent sample statements will once again be global so the next line per-
manently changes the workfile sample to “5 100”. Note that the last local smpl and subse-
quent smpl statement change the local sample only. When we exit the subroutine the
sample will be set to the last global sample of “5 100”.

User-Defined Dialogs
EViews offers the ability to construct several types of user-interface controls, or dialogs,
within your program. These dialogs permit users to input variables or set options during the
running of the program, and allow you to pass information back to users.

There are five different functions that create dialogs in EViews:


User-Defined Dialogs—179

• @uiprompt (p. 1166) – creates a prompt control, which displays a message to the
user.
• @uiedit (p. 1162) – creates an edit control, which lets users input text.
• @uilist (p. 1164) – creates a list control, which lets users select from a list of
choices.
• @uiradio (p. 1168) – creates a set of radio controls, which lets users select from a set
of choices.
• @uidialog (p. 1159) – creates a dialog which contains a mixture of other controls.
• @uifiledlg (p. 1163) – creates a open/save-style dialog to obtain the name of a file.

Each dialog function returns an integer indicating how the user exited the dialog:

User Selection Return Value


Cancel -1
OK 0
Yes 1
No 2

Note that the only dialog types that can return exit conditions other than “Cancel” or “OK”
are @uiprompt and @uidialog. If “Cancel” is pressed, the variables passed into the dialog
will not be updated with whatever settings the user has chosen. If “OK” is pressed, then the
dialog changes are accepted.

Each of the dialog functions accept arguments that are used to define what will be displayed
by the dialog, and that will be used to store the user's inputs to the dialog. You may use
string or a scalar arguments, where both the string and scalar can be a literal, a program
variable, or a workfile object.

@uiprompt
The @uiprompt(string prompt, string type) function creates a simple message/prompt box
that displays a single piece of text, specified using the prompt argument, and lets the user
click a button to indicate an action. The choices of action offered the user will depend upon
the string specified in type.
• if type is equal to “O”, or is omitted completely, then the dialog will only have an
“OK” button. This type of prompt dialog would typically be used to provide a message
to the user.
• if type is equal to “OC”, then the dialog will have an “OK” button and a “Cancel” but-
ton. This type of prompt dialog would be used to pass a message onto the user and let
them continue or cancel from the procedure.
180—Chapter 6.User-Defined Dialogs

• if type is equal to “YN”, then the dialog will contain a “Yes” button and a “No” button
which can be used to ask the user a question requiring an affirmative or negative
response.
• if type is equal to “YNC” the dialog will have a “Yes” button, a “No” button and a
“Cancel” button.

For example, the command:


@uiprompt("Welcome to EViews")

will display a simple dialog box with a simple welcome


message and an “OK” button, while the command
@uiprompt("Would you like to
continue", "YN")

displays a dialog asking the user if they would like to


continue the program, with a “Yes” or “No” answer.

Note that the arguments to the function may be a program variable or string object rather
than string literals. The following sets of commands give identical results to that above:
%type = "YN"
%msg = "Would you like to continue"
scalar ret = @uiprompt(%msg, %type)

The return value of the control is determined by the user response: Cancel (-1), OK (0), Yes
(1), No (2).

See @uiprompt (p. 1166) for additional detail.

@uiedit
The @uiedit(string IOString, string prompt, scalar maxEditLen) function provides an edit
control that lets the user enter text which is then stored in the string IOString. If IOString
contains text before the @uiedit function is called, the edit box will be initialized with that
text.

The string prompt is used to specify text to be displayed above the edit box, which may be
used to provide a message or instructions to the user.

maxEditLen is an option integer scalar that specifies the maximum length that IOString can
take. If the user tries to enter text longer than maxEditLen characters, the extra characters
will be truncated. By default maxEditLen is set to 32.

Both prompt and maxEditLen may be written in-line using string literals, but IOString must
be either a program variable or a string object in your workfile.

As an example,
User-Defined Dialogs—181

%eqname = "eq_unemp"
scalar ret = @uiedit(%eqname, "Enter a name for your equation")
equation {%eqname} unemp c gdp gdp(-1)

will display the following dialog box and then create an equation object with a name equal
to whatever was entered for %EQNAME.

The return value of the control is determined by the user response: Cancel (-1) or OK (0).

See @uiedit (p. 1162) for additional detail.

@uilist
This function creates a list box dialog, which lets the user select one item from a list. There
are two forms of the @uilist function, one that returns the user's selection as a string
IOString,
@uilist(string IOString, string prompt, string list)

and one that stores it as an integer IOScalar representing the position of the selection in the
list,
@uilist(scalar IOScalar, string prompt, string list)

The string prompt is used to specify text to be displayed above the list box, providing a mes-
sage or instructions to the user.

The string list is a space delimited list of items that will be displayed in the list box. To spec-
ify entries with spaces, you should enclose the entry in double-quotes using double-quote
escape characters.

Both prompt and list may be provided using in-line text, but IOString or IOScalar must be
either a program variable or an object in your workfile.

If the IO variable (IOString or IOScalar) is defined before the function is called, then the list
box control will have the item defined by the variable pre-selected. If the IO variable does
not match an item in the list box, or if it is not pre-defined, the first item in the list will be
selected.

The following program lines provide the user with a choice of robust standard errors, and
then displays that choice on the statusline:
%choice = "White"
182—Chapter 6.User-Defined Dialogs

%list = "Default White HAC"


scalar ret = @uilist(%choice, "Standard Errors Choice", %list)
statusline %list

Note that the above program could also be run with the following lines:
!choice = 2
%list = "Default White HAC"
scalar ret = @uilist(!choice, "Standard Errors Choice", %list)
%choice = @word(%list,!choice)
statusline %choice

The return value of the control is determined by the user response: Cancel (-1) or OK (0).

See @uilist (p. 1164) for details.

@uimlist
This function is similar to @uilist in that it creates a list box dialog, with a difference being
that here multiple selections from the list may be made. The form of the @uimlist function
is:
@uimlist(vector IOVector, string prompt, string list)

The string prompt is used to specify text to be displayed above the list box, providing a mes-
sage or instructions to the user.

The string list is a space delimited list of items that will be displayed in the list box. To spec-
ify entries with spaces, you should enclose the entry in double-quotes using double-quote
escape characters.

Both prompt and list may be provided using in-line text, but IOString or IOScalar must be
either a program variable or an object in your workfile.

If the IO variable (IOVector) is defined before the function is called, then the list box control
will have the items defined by the vector pre-selected. If the IO variable does not match an
item in the list box, or if it is not pre-defined, the first item in the list will be selected.

The following program lines provide the user with a choice of robust standard errors, and
then displays those choices on the statusline:
User-Defined Dialogs—183

vector(1) choice = 2
%list = "Default White HAC"
scalar ret = @uimlist(choice, "Standard Errors Choice", %list)
statusline %list

See @uimlist (p. 1165) for details.

@uiradio
@uiradio(scalar IOScalar, string prompt, string list) is similar to @uilist in that it pro-
vides a dialog that lets the user select from a list of choices. However rather than selecting
an item from a list box, the user must select the desired item using radio buttons. The
@uiradio function will return the user's choice in IOScalar.

The string prompt should be used to specify a message or instructions to the user to be dis-
played above the set of radio buttons.

The string list is a space delimited list of items that contains the items for the radio buttons.
To specify entries with spaces, you should enclose the entry in double-quotes using double-
quote escape characters.

Both prompt and list may be specified using in-line text, but IOScalar must be either a pro-
gram variable or an object in your workfile.

If IOScalar is defined and set equal to a valid integer before the function is called, the radio
button associated with that integer will be the default selection when the dialog is shown. If
IOScalar is not a valid choice, the first radio will be selected.

As an example, we replicate the standard error choice example from the @uilist function,
but this time use radio buttons:
!choice = 2
%list = "Default White HAC"
scalar ret = @uiradio(!choice, "Standard Errors Choice", %list)
%choice = @word(%list,!choice)
statusline %choice
184—Chapter 6.User-Defined Dialogs

The return value of the control is determined by the user response: Cancel (-1) or OK (0).

See @uiradio (p. 1168) for additional detail.

@uidialog
The @uidialog(control_spec1[, control_spec2, ….]) function displays a dialog which may be
composed of different controls, including simple text, edit boxes, list boxes, radio buttons
and check boxes. The dialog is specified using a list of control specifications passed into the
function as arguments. Each control specification is a type keyword specifying the type of
control, followed by a list of parameters for that control.

The type keywords should be from the following list:

Keyword Control
“caption” Dialog title
“text” Plain text
“edit” Edit box
“list” List box
“radio” Radio buttons
“check” Check box
“button” OK-type button
“buttonc” Cancel-type button
“colbreak” Column break
“setoc” Set OK/Cancel text

The “edit”, “list” and “radio” controls are similar to their individual dialog functions, and
the specifications for those controls follow the same pattern. Thus the specification for an
edit box would be (“edit”, string IOString, string prompt, scalar maxEditLen).

The “caption” control changes the title of the dialog, shown in the title bar. The caption
keyword should be followed by a string containing the text to be used as the caption, yield-
ing a specification of (“caption”, string caption).
User-Defined Dialogs—185

The “text” control adds basic text to the dialog. Like the caption control, the text control
keyword, “text”, should be followed by a string containing the text to be used, yielding a
specification of (“text”, string text).

The “check box” control adds a check box to the dialog. The check keyword should be fol-
lowed by a scalar, IOScalar, which stores the selection of the check box - 1 for checked, and
0 for unchecked, and then by a string prompt which contains the text to be used as a
prompt/instructions for the check box. The specification for the check box control is then:
(“check”, scalar IOScalar, string prompt).

The “button” and “buttonc” controls add a custom button to the dialog. The dialog will
close after a button has been pressed. The behavior of the button will depend on the type of
button —buttons of type “button” will behave in the same way as the “OK” button (i.e., all
variables passed into the dialog will be updated to reflect changes made to their correspond-
ing controls). Buttons of type “buttonc” will behave in the same way as the “Cancel” button
(i.e., all variables will be reset to the values that were passed into the dialog).

The return value of the dialog will correspond to the order in which buttons are placed in
the dialog. If only one button (apart from the standard “OK” and “Cancel”) is included in
the dialog, the return value for that button will be “1”. If there is more than one button, then
the first button will return a value of “1”, the second will return a value of “2” and so on.
Note that the return value is independent of whether the button was of type “button” or
“buttonc”. The specification for the button controls is (“button[c]”, “text”) where text speci-
fies the text that will be on the button.

The column break control inserts a column break. By default, EViews will automatically
choose the number of columns in the constructed dialog. There is still a maximum of only
two columns allowed, but by adding a “colbreak” control, you can force the position of a
break in the dialog.

“setoc” allows you to change the text of the “OK” and “Cancel” buttons on the dialog. You
should supply two words, separated by a space as the text for “OK” and “Cancel”.

As an example, a dialog that offers a choice of covariance matrix options, plus a check box
for degree of freedom adjustment, could be made with:
!choice = 2
!doDF = 1
%list = "Default White HAC"
scalar ret = @uidialog("caption", "Covariance Options", "list",
!choice, "Covariance method", %list, "check", !doDF, "DF-
adjust")
186—Chapter 6.User-Defined Dialogs

See @uidialog (p. 1159) for details.

@uifiledlg
The @uifiledlg(string IO_Filespec, string filter, string style) displays a standard Windows
file open or save dialog so that you may obtain the path and name of a file.

@uifiledlg function will return the user's specification in file_spec.

The string IO_Filespec should be used to specify an initial location and possibly the name for
the file. IO_Filespec will also contain the file specified on return.

The string filter is used to specify the types of files to show in the dialog using the filter argu-
ment, with, for example, “” used to denote all files, and “prg” used to limit the display to
files ending in “.prg”.

The type argument is used to determine whether the shown dialog has an “open” or a
“save” prompt.

(Note that the clicking OK on the dialog does not actually open or save the selected file, it
merely returns the name of the selected file. Thus, specifying the type argument is for cos-
metic reasons only.)

Both filter and style may be specified using in-line text, but IO_Filespec must be either a pro-
gram variable or an object in your workfile.

The displayed dialog will display both an OK and a Cancel button, and will return an inte-
ger representing the button clicked: Cancel (-1), OK (0).
string myfile = "c:\temp\"
@uifiledlg(myfile, "prg”, "open")

These commands display a file open dialog style containing a list of all files with a “.prg”
extension in the folder “c:\temp\”. The user can navigate through the file system and select
another file, whose path and name will be returned in the string MYFILE.

Note that the slightly different set of commands


string myfile = "c:\temp"
@uifiledlg(myfile, "prg", "save")
User-Defined Dialogs—187

will instead display a save dialog that opens in the “c:\” folder with the filename initialized
to “temp.prg” (MYFILE does not have the trailing “\”).

See also @uifiledlg (p. 1163).

Example Program
This program creates a workfile and some series, then puts up dialogs asking the user to
specify the dependent variable and the regressors to be used in a least-squares equation.
Note that the part of the example program that generates the data could be replaced with a
command to open up an existing workfile.
'Create a workfile and some series
wfcreate temp u 100
series y=nrnd
series x=nrnd
series w=nrnd
'-------------------------------------
'variable to store name of dependent variable
%dep = ""
'variable to store list of regressors. Default is "c" for a con-
stant.
%regs = "c "
'variable that will track the result of dialogs. -1 indicates user
hit Cancel. 0 Indicates user hit OK.
!result = 0
'put up an Edit dialog asking for dependent variable.
!result = @uiedit(%dep,"Enter the dependent variable")
if !result=-1 then 'if user cancelled, then stop program
stop
endif
'put up an Edit dialog asking for regressors list.
!result = @uiedit(%regs,"Enter the list of regressors")
if !result=-1 then 'if user cancelled, then stop program
stop
endif

equation eq1.ls {%dep} {%regs} 'estimate equation.

Three program variables are used in this program: %DEP, %REGS and !RESULT. %DEP is
the string variable that will contain the user’s entry for the dependent variable. To begin, we
set this equal to an empty string. %REGS is used to store the user’s entry for the list of
188—Chapter 6.Version 4 Compatibility Notes

regressors. We set this equal to “C” to begin with. This means that the default setting for the
regressor list will be a constant. !RESULT will be used to track the completion of the dialogs.
Every dialog returns an integer value depending on whether the user clicked OK or Cancel
(or in some cases Yes or No). We initialize this value to 0.

Following the declaration of the variables, the first dialog


is brought up using the @uiedit command. This will cre-
ate an Edit dialog asking the user to “Enter the dependent
variable.” The user’s response will be stored in %DEP. Fol-
lowing the dialog command, we check whether the value
of !RESULT is equal to -1. A -1 indicates that the user
pressed Cancel in the dialog. If this is the case, the program quits, using the stop com-
mand.

The second dialog command is similar to the first, but rather than asking for the dependent
variable, it asks the user to “Enter the list of regressors,” and stores that list in %REGS. Note
that since %REGS was set equal to “C” prior to the dialog being put up, the dialog will be
pre-filled with the constant term. Users can still delete the constant or add extra regressors.

Finally, having obtained entries for both %DEP and %REGS, equation EQ1 is estimated via
least squares with the specified variables.

Version 4 Compatibility Notes


While the underlying concepts behind strings, string variables, and replacement variables
have not changed since the first version of EViews, there were three important changes in
the implementation of these concepts introduced in EViews 5. In addition, there has been an
important change in the handling of boolean comparisons involving numeric NA values,
and blank string values.

String vs. Replacement Variables


First, the use of contextual information to distinguish between the use of string and replace-
ment variables has been eliminated.

Prior to EViews 5, the underlying notion that the expression “%X” refers exclusively to the
string variable %X while the expression “{%X}” refers to the corresponding replacement
variable was modified slightly to account for the context in which the expression was used.
In particular, the string variable expression “%X” was treated as a string variable in cases
where a string was expected, but was treated as a replacement variable in other settings.

For example, suppose that we have the string variables:


%y = "cons"
%x = "income"
Version 4 Compatibility Notes—189

When used in settings where a string is expected, all versions of EViews treat %X and %Y
as string variables. Thus, in table assignment, the command,
table1(2, 3) = %x + " " + %y

is equivalent to the expression,


table1(2, 3) = "cons" + " " + "income"

However, when string variables were used in other settings, early versions of EViews used
the context to determine that the string variable should be treated as a replacement variable;
for example, the three commands
equation eq1.ls %y c %x
equation eq1.ls {%y} c {%x}
equation eq1.ls cons c income

were all viewed as equivalent. Strictly speaking, the first command should have generated
an error since string variable substitution would replace %Y with the double-quote delim-
ited string “cons” and %X with the string “income”, as in
equation eq1.ls "cons" c "income"

Instead, EViews determined that the only valid interpretation of %Y and %X in the first
command was as replacement variables so EViews simply substituted the names for %Y and
%X.

Similarly, the commands,


series %y = %x
series {%y} = {%x}
series cons = income

all yielded the same result, since %Y and %X were treated as replacement variables in the
first line, not as string variables.

The contextual interpretation of string variables was convenient since, as seen from the
examples above, it meant that users rarely needed to use braces around string variables. The
EViews 5 introduction of alphanumeric series meant, however, that the existing interpreta-
tion of string variables was no longer tenable. The following example clearly shows the
problem:
alpha parent = "mother"
%x = "parent"
alpha temp = %x

Note that in the final assignment statement, the command context alone is not sufficient to
determine whether %X should refer to the string variable value “parent” or to the replace-
ment variable PARENT, which is an Alpha series containing the string “mother”.
190—Chapter 6.Version 4 Compatibility Notes

Consequently, in EViews 5 and later, users must now always use the expression “{%X}” to
refer to the replacement variable corresponding to the value of %X. Thus, under the new
interpretation, the final line in the example above resolves to
alpha temp = "parent"

Under the EViews 4 interpretation of the final line, “%X” would have been treated as a
replacement variable so that TEMP would contain the value “mother”.

To interpret the last line as a replacement variable in EViews 5 and later, you must now
explicitly provide braces around the string variable
alpha temp = {%x}

to resolve to the command


alpha temp = parent

String Variables in String Expressions


The second major change in EViews 5 is that text in a string expression is now treated as a
literal string. The important implication of this rule is that string variable text is no longer
substituted for inside a string expression.

Consider the assignment statements


%b = "mom!"
%a = "hi %b"
table(1, 2) = %a

In EViews 4 and earlier, the “%B” text in the string expression was treated as a string vari-
able, not as literal text. Accordingly, the EViews 4 string variable %A contains the text “hi
mom!”. One consequence of this approach is that there was no way to get the literal text of
the form “%B” into a string using a program in EViews 4.

Beginning in EViews 5, the “%B” in the second string variable assignment is treated as lit-
eral text. The string variable %A will contain the text “hi %b”. Obtaining a %A that con-
tains the EViews 4 result is straightforward. Simply move the first string variable %B outside
of the string expression, and use the string concatenation operator:
%a = "hi " + %b

assigns the text “hi mom!” to the string variable %A. This expression yields identical results
in all versions of EViews.

Case-Sensitive String Comparison


In early versions of EViews, program statements could involve string comparisons. For
example, you might use an if-statement to compare a string variable to a specific value, or
you could use a string comparison to assign a boolean value to a cell in a matrix or to a
Version 4 Compatibility Notes—191

numeric series. In all of these settings, the string comparisons were performed caselessly, so
that the string “Abc” was viewed as equal to “ABC” and “abc”.

The introduction of mixed case alpha series in EViews 5 meant that caseless string compari-
sons could no longer be supported. Accordingly, the behavior has been changed so that all
EViews 5 and later string comparisons are case-sensitive.

If you wish to perform caseless comparison in newer versions of EViews, you can use the
@upper or @lower string functions, as in
if (@lower(%x) = "abc") then

or
if (@upper(%x) = "ABC") then

Alternately, programs may be run in version 4 compatibility mode to enable caseless com-
parisons for element operations (see “Version 4 Compatibility Mode” on page 192). For
example, the if-statement comparison:
if (%x = "abc") then

will be performed caselessly in compatibility mode.

Note that compatibility mode does not apply to string comparisons that assign values into
an entire EViews series. Thus, even in compatibility mode, the statement:
series y = (alphaser = "abc")

will be evaluated using case-sensitive comparisons for each value of ALPHASER.

Comparisons Involving NAs/Missing Values


Prior to EViews 5, NA values were always treated as ordinary values for purposes of
numeric equality (“=”) and inequality (“<>”) testing. In addition, when performing string
comparisons in earlier versions of EViews, empty strings were treated as ordinary blank
strings and not as a missing value. In these versions of EViews, the comparison operators
(“=” and “<>”) always returned a 0 or a 1.

In EViews 5 and later, the behavior of numeric and string inequality comparisons involving
NA values or blank strings has been changed so that comparisons involving two variables
propagate missing values. To support the earlier behavior, the @eqna and @neqna functions
are provided so that users may perform comparisons without propagating missing values.
Complete details on these rules are provided in “String Relational Operators” on page 87 of
the Command and Programming Reference and in “Numeric Relational Operators” on
page 198 of User’s Guide I.

Programs may be run in version 4 compatibility mode to enable the earlier behavior of com-
parisons for element operations. For example, the if-statement comparison:
192—Chapter 6.References

if (!x = !z) then

will not propagate NA values in compatibility mode.

Note that compatibility mode does not apply to comparisons that assign values into an
EViews numeric or alpha series. Thus, even in compatibility mode, the statement:
series y = (x = z)

will propagate NA values from either X or Z into Y.

Version 4 Compatibility Mode


While the changes to the handling of string variables and element boolean comparisons are
required for extending the programming language to handle the new features of the EViews
5 and later, we recognize that users may have a large library of existing programs which
make use of the previous behavior.

Accordingly, EViews provides a version 4 compatibility mode in which you may run EViews
programs using the previous context sensitive handling of string and substitution variables,
the earlier rules for resolving string variables in string expressions, and the rules for caseless
string comparison and propagation of missing values in element comparisons.

There are two ways to ensure that your program is run in version 4 compatibility mode.
First, you may specify version 4 compatibility mode at the time the program is run. Compat-
ibility may be set interactively from the Run Program dialog (“Executing a Program” on
page 133) by selecting the Version 4 compatible variable substitution and program bool-
ean comparisons checkbox, or in a program using the “ver4” option (see run (p. 581)).

Alternatively, you may include “MODE VER4” statement in your program. See “Program
Modes” on page 151 for details.

References
Davidson, Russell and James G. MacKinnon (1993). Estimation and Inference in Econometrics, Oxford:
Oxford University Press.
Greene, William H. (2008). Econometric Analysis, 6th Edition, Upper Saddle River, NJ: Prentice-Hall.
Chapter 7. External Connectivity

EViews offers several methods for interacting with external applications and data:
• The EViews OLEDB driver provides an easy-to-use interface for external programs to read
data stored in EViews workfiles (WF1) and EViews databases (EDB) (“The OLEDB Driver”
on page 194).
• The EViews Excel Add-in offers a simple interface for reading data stored in EViews work-
files and databases from within Microsoft Excel (“The Excel Add-in” on page 194).
• The EViews Database Objects (EDO) Library gives you the ability to access data objects
held inside EViews databases and workfiles from within an external application (“EViews
Database Objects (EDO) Library” on page 194).
• EViews offers COM Automation server support so that external programs or scripts can
launch or control EViews, transfer data, and execute EViews commands (“EViews COM
Automation Server” on page 195).
• EViews offers COM Automation client support for MATLAB, R, and Python application
servers so that EViews may be used to launch and control the application, transfer data,
and execute commands (“EViews COM Automation Client Support (MATLAB, R, Python)”
on page 195).
• EViews offers an EViews Database Extension (EDX) interface for developers who wish to
provide EViews access to their database formats. Any external data source that imple-
ments this interface can be opened directly from within EViews just like an EViews data-
base (“EViews Database Extension Interface” on page 203).
• EViews can be used as a Jupyter kernel. EViews code can be run and the results displayed
from within a Jupyter notebook, allowing users to take advantage of all its interactive and
easy-to-use research, analysis, presentation, and record-keeping features (“Jupyter Note-
book Support” on page 205).

Reading EViews Data


EViews offers a variety of ways for you to access data stored in EViews workfiles (WF1) and
EViews databases (EDB) from external sources.

The EViews OLEDB driver provides an easy way for OLEDB-aware clients or custom programs to
read EViews data

Alternatively, the EViews Microsoft Excel Add-in allows users to fetch and link to EViews data
located in workfiles and databases. The Add-in offers an easy-to-use interface to OLEDB for read-
ing EViews data from within Excel.
194—Chapter 7.Reading EViews Data

Lastly, you may use the EViews Database Objects Library to access EViews data from within
an external application.

The OLEDB Driver


The EViews OLEDB driver is automatically installed and registered on your computer when
you install EViews. Once installed, you may use OLEDB-aware clients or custom programs
to read series, vector, and matrix objects directly from EViews workfiles and databases.

See “The OLEDB Driver” on page 175 of User’s Guide I for discussion. For additional details,
see the Using the EViews OLEDB Driver whitepaper available from our website
www.eviews.com/download/download.html.

The Excel Add-in


The EViews Excel Add-in offers a simple interface for fetching and linking to data stored in
EViews workfiles and databases from within Microsoft Excel (2000 and later).

See “The Excel Add-in” on page 172 of User’s Guide I for discussion. For additional details,
see the Using the EViews OLEDB Driver whitepaper available from our website
www.eviews.com/download/download.html.

EViews Database Objects (EDO) Library


The EViews Database Objects (EDO) Library provides access to data objects held inside
EViews databases and workfiles from within an external application.

EDO library support is not available in EViews Standard Edition.

The library consists of a set of COM objects exported by EViews that can easily be used in a
variety of development environments such as Microsoft .NET and Visual Basic for Applica-
tions (VBA).

The EDO API provides full read and write access to EViews databases, as well as read-only
access to EViews workfiles. The interface provides access to both the observation values and
the attributes of an object. In contrast, the EViews OLEDB interface “The OLEDB Driver” on
page 194 offers data reading support but not write operations nor object attributes.

The EDO library supports reading and writing of the following EViews data objects:
• Numeric series (including series containing dates)
• Alpha series (containing character data)
• Scalars
• Vectors
• Matrices
EViews COM Automation Client Support (MATLAB, R, Python)—195

• Strings
• String Vectors

The library does not currently support access to data within structured EViews objects such
as equations or models.

For additional details, see the EViews Data Objects Library whitepaper, available from our
website www.eviews.com/download/download.html.

EViews COM Automation Server


EViews may be used as a COM Automation server so that an external program or script may
launch and control EViews programmatically. EViews COM is comprised of two class
objects: Manager and Application.

The Manager class is used to manage and create instances of the main EViews Application
class. The Application class provides access to EViews functionality and data. Most notably,
the Application class Run and a variety of Get and Put methods provide you with access to
EViews commands and allow you to obtain read or write access to series, vectors, matrix,
and scalar objects.

You may, for example, use, the pyeviews package allows you to call EViews from Python.
See the whitepaper http://www.eviews.com/download/whitepapers/pyeviews.pdf for more
information about the pyeviews package.

For a complete description of these methods, please refer to the EViews COM Automation
Server whitepaper, available from our website www.eviews.com/download/download.html.

Note that web server access to EViews via COM is not allowed. Furthermore, EViews will
limit COM access to a single instance when run by other Windows services or run remotely
via Distributed COM.

EViews COM Automation Client Support (MATLAB, R, Python)


EViews offers COM Automation client support for select external application servers. Sup-
port is currently provided for three applications: MATLAB, R, and Python.

The client support includes a set of EViews functions for exporting EViews data to the exter-
nal application, running commands and programs in the application, and importing data
back into EViews. These functions provide easy access to the powerful programming lan-
guages of MATLAB, R, and Python to create programs and routines that perform tasks not
currently implemented in EViews. The interface also offers access to the large library of sta-
tistical routines already written in the MATLAB, R, and Python languages.
196—Chapter 7.EViews COM Automation Client Support (MATLAB, R, Python)

There are nine EViews commands that control the use of external applications: xclose
(p. 668), xget (p. 668), xlog (p. 671), xopen (p. 672), xput (p. 675), xon (p. 672), xoff
(p. 671), xpackage (p. 674), and xrun (p. 677).

xopen and xclose are used to open and close a connection to the external application
(MATLAB or R). xput and xget are used to send data to and from the external application.
xrun is used to send a command to the external application, and, finally, xlog lets you
show or hide an external application log window within EViews.

Using MATLAB®
To open a connection to MATLAB, simply use the xopen(type=m) command. EViews will
then attempt to launch MATLAB on your computer. Note, your computer must have access
to MATLAB, either through a local installation, or through a network. EViews has been
tested with MATLAB release R2008a, although other versions may work as well.

Once a connection to MATLAB has been made, xput (p. 675) may be used to pass data from
EViews over to MATLAB. All numerical data is passed to MATLAB as a matrix. String data
(in the form of an alpha series or svector) will be passed to a MATLAB char if each string
contains the same number of characters. Otherwise the string data will be passed as a cell
array. Series and group objects are always filtered by the current sample unless you specify
an explicit sample in the xput command.

Note that object names in EViews are not case sensitive. Unless otherwise specified, EViews
objects that are passed into MATLAB using xput will have the same name as the EViews
objects that are being pushed, with the case determined by the case established for the COM
connection (see xopen (p. 672)).

xrun can be used to issue a single line command to MATLAB. You may, for example, use
xrun to invert a matrix or run a program in MATLAB. If you wish to run multiple com-
mands, each command must be entered with a separate xrun command. Commands should
be surrounded in quotes.

xget can be used to fetch data from MATLAB into EViews. The “type=” option lets you
specify the type of object that will be created in EViews. If no option is specified, MATLAB
matrices will be brought in as EViews matrix objects, while chars and cell arrays will be
brought in as svectors. If you use “type=series” or “type=alpha” to specify that the data is
brought in as a series or an alpha series, EViews will create a series of workfile length, and
either truncate the data, or pad with NAs, if the incoming matrix does not have the same
number of rows as there are workfile observations.

The follow program offers a simple example using MATLAB to perform a least-squares
regression (more complicated operations may be performed by using xrun to run a MATLAB
program):
'create a workfile
EViews COM Automation Client Support (MATLAB, R, Python)—197

wfcreate u 100
'create some data
series y=nrnd
series x1=nrnd
series x2=nrnd
'group regressor data into a group
group xs c x1 x2
'open a connection to Matlab with lower-case default output names
xopen(type=m, case=lower)
'put regressors and dependent variable into Matlab
xput xs
xput y
'run a command to perform least squares as a matrix operation
xrun "beta = inv(xs'*xs)*xs'*y"
'retrieve betas back into EViews
xget beta
'perform same least squares estimation in EViews
equation e1.ls y xs
show e1
show beta
'close Matlab connection
xclose

The program first creates a new workfile, and then creates some series objects. The series
called Y is the dependent variable, and the series X1 and X2 are the regressors (along with a
constant). xopen is used to open a connection to MATLAB, and then xput is used to pass
the dependent variable and the regressors over to MATLAB. Note that the names of the
matrices and vectors will all be lower-cased in MATLAB since the connection was opened
with the “case=lower” option.

xrun is used to create a vector in MATLAB, called “beta”, equal to the least squares coeffi-
cient, using the matrix algebra formula for LSQ. beta is brought back into EViews with the
xget command, and then we estimate the same equation inside EViews and show the two
results for comparison. Finally the connection to MATLAB is closed.

Using R
R is a GNU-project software environment for statistical computing and graphics. R is free
software (under the terms of the GNU General Public License) that is readily available for
198—Chapter 7.EViews COM Automation Client Support (MATLAB, R, Python)

download from the Official R Project website: http://www.r-project.org/ and other mirror
sites.

To use the EViews external interface to R, you must have R installed on your Windows com-
puter. Once installed, you may use the commands listed above to communicate with R from
within EVIews.

EViews 14 supports R integration directly, eliminating the need for any third party software.
Install both EViews 14 and R on the same computer and use normal EViews commands,
such as XOPEN and XRUN.

Installing R
EViews was developed and tested with R version 3.2.3. You must have version 3.2.3 or
newer installed on the machine running EViews.

If you do not currently have R installed, simply go to the following site and download the
latest version:
https://cran.r-project.org

Verifying EViews R Connector


Verify that the new EViews R Connector Interface components are properly registered by
running the EViews command REGCOMPONENTS:

In the Register Components dialog, make sure that the EViews R Connector Interface objects
have been properly registered. If not, click the Yes (All) button to re-register these compo-
nents on your local machine, then re-run REGCOMPONENTS to verify the registration. Note:
EViews COM Automation Client Support (MATLAB, R, Python)—199

Registration of these components will require local administrator rights. If you do not have
these admin rights, please contact your IT department for support.

Next, go to the External Program Interface dialog under the Options menu/General
Options/External Program Interface:

In COM ProgID group, make sure that EViewsRConn.VariantRConn is selected for R.

Next, if Home Path is blank, click the […] button and navigate to your local R installation.
Select the version-specific R folder (e.g., “R-3.2.3”) under the parent R folder as your home
directory.

Optionally, you can also select your Save Series as preference when pushing EViews series
objects into R. If you select “ts (time series)”, series objects that have a compatible R ts fre-
quency will be pushed as R ts objects. Otherwise, an R data.frame structure will be created
instead.

Now we're ready to begin using R.

Opening a Connection to R
All external program interface methods must begin with a call to XOPEN:
XOPEN(type=r)

This will begin a new session of R and, by default, an associated RConn Output log window
should appear. This log window will show any R commands we run and any output gener-
ated by R. You can also type R commands interactively into the RConn log window.
200—Chapter 7.EViews COM Automation Client Support (MATLAB, R, Python)

Now that we have an open connection to R, we can use the other 'X' methods to perform
some actions.

Sending EViews Data to R


Now that we have an open connection to R, we can send EViews object(s) to R using the
XPUT command:
XPUT(rtype=data.frame, name=vars) y x1 x2

Basic EViews object types such as series, alphas, matrices, vectors, and scalars can be
pushed successfully to R. Depending on the EViews object type, an appropriate R object will
be created when the data is sent. As our example shows, XPUT also supports grouping mul-
tiple series objects into a single R time series or R data.frame object.

Running an R Command
Now that we have some data in R, we can run R specific commands by using the XRUN com-
mand:
XRUN z<-glm(y~x1+x2, family=Gamma(link=log), data=vars)

You can also type this command directly into the bottom of the RConn log window (without
XRUN):

XON and XOFF Commands


To run multiple R commands without having to specify XRUN on each line of an EViews pro-
gram, you can use the XON and XOFF commands (introduced in EViews 10) to control exter-
nal programming mode. Once you call XON, all program lines after that will be sent to R
directly. Use XOFF (or XCLOSE) to turn this mode off.
XON 'Turn on external programming mode
z<-glm(y~x1+x2, family=Gamma(link=log), data=vars) summary(z)
XOFF 'Turn off external programming mode
EViews COM Automation Client Support (MATLAB, R, Python)—201

Output Display
Note that our connector does not always automatically capture all of your R output. Conse-
quently, you may find that using XRUN to issue a command that displays output in R may
return only a subset of the usual output to your log window. In the most extreme case, you
may see a simple "OK" message displayed in your log window. To instruct R to show all of
the output, you should use enclose your command inside an explicit print statement in R.
Thus, to display the contents of a matrix X, you must issue the command
XRUN print(X)

instead of the more natural


XRUN X

Retrieving R Data into EViews


To retrieve data back into EViews, we will use the XGET command:
XGET(name=beta, type=vector) z$coef

Closing the R Connection


Once we've completed our R operations, we can close our connection with a simple call to
XCLOSE:
XCLOSE

Ability to Save EViews Workfile as RDATA Workspace File


EViews also has native RDATA workspace file compatibility.

This means you can save an EViews workfile (one page at a time) directly to a new RDATA
workspace file:
wfsave(type=rdata) c:\files\tq.rdata

Each simple object (series, alpha, matrix, vector, and scalar) on the current workfile page
will be converted to an appropriate R data structure and saved into the new RDATA file.

You can also open a pre-existing RDATA file as an EViews workfile, though because this
operation can only open all R objects into a single workfile page, all the objects in the
RDATA file must be the same frequency for this to work properly.

In cases where there are R objects with different frequencies, it would be better to treat the
RDATA file as an EViews Database instead.

Open RDATA Workspace File as an EViews Database


In EViews 14, you can now open an RDATA workspace file as an EViews Database:
DBOPEN(type=rdata) c:\files\data.rdata
202—Chapter 7.EViews COM Automation Client Support (MATLAB, R, Python)

This will open the RDATA file in its own EViews database window. You can view all the R
objects found in this database and individually FETCH the objects you want into your work-
file:

Note: R data structures that could have multiple columns/elements (such as data.frame, list,
and mts objects) are listed once per column/element with the appropriate R name.

As an EViews Database, you can use both FETCH and STORE to read and write data to the
RDATA file and even link EViews series objects back to their source R structure to allow for
simple data refreshes.

R Related Links
The Official R Project website: http://www.r-project.org/

Using Python
EViews allows you to use Python packages and code from within EViews to improve your
workflow. With EViews, you can send EViews data into the Python environment, execute
Python functions, and then retrieve data back into EViews with simple commands.

EViews supports Python 2 (version 2.7.15 or greater) and Python 3 (version 3.6.5 or
greater).

The syntax for the Python related xopen options is:


XOPEN(p)

or
XOPEN(type=p)
EViews Database Extension Interface—203

We support the following Python data types:


list
tuple
dictionary
numpy.ndarray
pandas.series
pandas.dataframe

The last three lines require the prior installation of the numpy and the pandas Python pack-
ages.

The syntax for Python related xput commands is therefore:


xput(ptype=list|tuple|dictionary|ndarray|series|dataframe)

EViews Database Extension Interface


EViews offers built-in support for a handful of foreign database formats (e.g. DataStream,
Haver, FRED, etc.), providing users direct access to data in these formats via the standard
EViews database interface (“Foreign Format Databases” on page 362 of User’s Guide I).

If data reside in unsupported database formats, users can resort to ODBC (if an ODBC driver
was available) or using an intermediate file format (such as XLS, CSV or HTML) or the Win-
dows clipboard to exchange data. These approaches are less convenient than working with
the standard interface, and there are a number of limitations, including the inability to
obtain additional attributes such as source, units, etc. alongside observation values and the
fact that data brought into EViews using these approaches cannot be "linked” back to the
source to allow for automatic refreshes when a workfile is loaded.

To overcome these limitations, EViews supports the EViews Database Extension (EDX) Inter-
face which allows an external data source that implements this interface to be opened from
within EViews and used just like an EViews database.
204—Chapter 7.EViews Database Extension Interface

Programmers who implement a database extension for an external database format can
extend EViews so that:
• an EViews user can ask what objects the external database contains
• an EViews user can read data objects from the external database
• an EViews user can write data objects to the external database
• an EViews user can browse through the contents of the external database using a cus-
tom graphical interface developed specifically for the data source

Using EDX, a developer can offer EViews access to a external database that is indistinguish-
able from built-in access to data sources. Notably, EViews built-in support for connecting to
the U.S. Energy Information Administration (EIA) on-line databases was developed using an
EDX interface to the EIA API.

More precisely, EDX is a set of COM interfaces. Supporting a new format involves creating a
small library (usually housed in a DLL) that contains COM objects that implement these
interfaces. The library can be developed in many different programming environments
including native C++ and Microsoft .NET. These COM objects are used by EViews to inter-
act with the underlying database.
Jupyter Notebook Support—205

For details and extensive examples of the EDX interface, please see the whitepaper EViews
Database Extension Interface Release x.x (available from our website www.eviews.com/
download/download.html).

Jupyter Notebook Support


Jupyter is a popular free, open-source, web-based interactive development environment that
allows users to create notebooks for documenting computational workflow. A notebook con-
sists of an ordered series of input and output cells for the organization of code, explanatory
text, and multimedia in a single document. The chronological, narrative record-keeping a
notebook allows for are useful for analysis, reporting, teaching, documentation, and many
other purposes.

The code in a notebook cell is passed to a programming language specific “kernel” on the
backend that does the code execution. EViews, starting with version 13, can be used as a
Jupyter kernel. Users can run an EViews program and display its results from within a note-
book.

Using the EViews Jupyter Kernel


After Python and Jupyter have been installed (https://jupyter.org/), make the EViews kernel
available to Jupyter by going to the main EViews menu and selecting Options/General
Options/External program interface. Click the Publish Jupyter Notebook button.
206—Chapter 7.Jupyter Notebook Support

A new EViews-specific folder will be created in the Jupyter kernels folder location, usually
found at “%AppData%/Roaming/jupyter/kernels”.

Next, run the notebook server. Depending on your installation, this can be done from a com-
mand prompt or the start menu in Windows or from Anaconda Navigator. Select the EViews
kernel by choosing it from the “New” drop-down menu in the upper-right corner of the
notebook dashboard. This will open the notebook editor, the interface where code and other
input is entered and evaluated. Type EViews commands into the cells and run them with
shift-enter (to run the current cell and select the following cell) or ctrl-enter (to run the cur-
rent cell). More information on using Jupyter can be found in the Jupyter documentation
(https://jupyter-notebook.readthedocs.io/en/stable/notebook.html).
Chapter 8. Add-ins

In Chapter 6. “EViews Programming,” beginning on page 129, we explained how you can
put commands in program files to repeat tasks, produce a record of your research project, or
augment the built-in features of EViews.

This chapter describes Add-ins, which extend the utility of the programming tools by provid-
ing seamless access to programs from the standard EViews menus and command line. Creat-
ing an Add-in is a simple procedure and involves little more than defining a command and
menu items for your existing EViews program.

Keep in mind that Add-ins aren’t just for EViews programmers. Even if you have never writ-
ten an EViews program, you may take advantage of these tools by installing prepackaged
Add-ins from the S&P EViews website or from third-parties. Once installed, Add-ins can pro-
vide you with user-defined features that are virtually indistinguishable from built-in EViews
features.

What is an Add-in?
Fundamentally, an Add-in is simply an EViews program that is integrated into the EViews
menus and command line, allowing you to execute the program using the menus or user-
defined command. In this regard, any EViews program can be used as the basis of an Add-
in.

More specifically, the Add-ins infrastructure lets you:


• add entries to EViews global or object-specific menus to offer point-and-click execu-
tion of the Add-in program.
• specify a user-defined single-word global or object-specific command which may be
used to run the Add-in program.
• display Add-in output in standard EViews object windows.

For example, suppose you have created a program to implement an econometric procedure
that prompts the user for needed input. You may turn this program into an EViews Add-in
that may be run by selecting a menu item or typing a command. Lastly, the Add-in might
display the output in the window of an existing EViews object.

Getting Started with Add-ins


The easiest way to get started with Add-ins is to download and install one of the previously
written Add-ins packages from the EViews website. Simply go to the main menu in EViews
and select Add-ins/Download Add-ins...
208—Chapter 8.Getting Started with Add-ins

EViews will open the corresponding Add-ins dialog opened to the Available tab showing
the list of Add-ins that are available for download from the EViews.com website. The list
shows the name of the Add-in, the publication date, version, and status. The status field
indicates whether the entry has not been installed (blank), has previously been installed, or
has previously been installed and is out-of-date.
Getting Started with Add-ins—209

Select the desired entry to display additional information in the bottom of the dialog and to
enable the Install button. Clicking on Install instructs EViews to download the Add-in and
begin the installation procedure. (Alternately, you may click on the Website button and fol-
low the navigation links to the Add-ins page. Download the appropriate file to your com-
puter then open it using EViews by double-clicking on the file or dropping it onto the
EViews application window or the application icon.)

The first step in the


installation procedure is
to unpack the Add-in
files onto your computer.
By default, EViews will
put the files in a sub-
folder of your default
directory (see “Manag-
ing Add-ins” on page 220), but you may choose an alternate location if desired (you may
use the “...” button on the right-hand side to navigate to a specific directory). Click on OK to
proceed.

Note that if you manually downloaded the Add-in from the EViews website, you need not
use EViews to unpack the files. You may instead change the download file extension from
210—Chapter 8.Getting Started with Add-ins

“AIPZ” to “ZIP” and use your favorite ZIP file tools to extract the contents into the desired
directory.

Next, EViews will prompt you to run the installation program that is included in the Add-in
package.

The installation pro-


gram is a file contain-
ing EViews
commands that auto-
matically registers
the Add-in by defin-
ing menu entries and
commands for the
program.

If you click on No in response to the prompt, EViews will finish the automatic installation
procedure without running the installation program and registering the Add-in. The Add-in
program files will be on your computer but will not be integrated into the standard com-
mand or menu interface. You may, at a later time, examine and run the installation program
as you would any other EViews program, or you may manually register your programs as
described in “Registering an Add-in” on page 223.

Click on Yes to display other add-in options and to finish registering the Add-in. If there are
conflicts with existing directory names or existing Add-ins, EViews will warn you before pro-
ceeding.

After completion of the automatic installation procedure, EViews will report that the Add-in
was installed successfully:

We note that installing and running an EViews program file provided by an unknown indi-
vidual has risks. Accordingly, we recommend that care be taken when installing packages
from non-trusted sites. All of the packages provided on the EViews website have been exam-
ined to ensure that they do not include potentially harmful commands.

Once your Add-in is installed, you may wish to consult the Add-in documentation to obtain
additional information on features, options, and commands. Open the Add-ins management
Using Add-ins—211

dialog by selecting Add-ins/Manage Add-ins... from the main EViews menu, select the Add-
in of interest and click on the Docs button to display any documentation provided by the
author:

Using Add-ins
Add-ins are integrated into the EViews menus and command line so that they work much
like built-in routines. To run an Add-in program, simply select the corresponding menu entry
or issue the appropriate command.

Beyond that, working with Add-ins menu and command entries does require some under-
standing of the difference between the two types of Add-ins: object-specific and global. As
the names suggest, object-specific Add-ins are designed to work with a single object type,
while global Add-ins are designed to work more generally with more than one object or
object type.

For example, an Add-in that computes a spline using data in a series is likely to be object-
specific, since it operates on a single series, while an Add-in that copies tables, graphs, and
spools into an RTF file would naturally be defined as global.

The menu entries and form of commands differs between the two Add-in types.
212—Chapter 8.Using Add-ins

• Global Add-ins have menu entries that appear only in the main Add-ins menu. Global
add-in commands follow the EViews command syntax:
command(options) [args]
• Object-specific Add-ins have menu entries that appear in both the main Add-ins menu
and in the menu of objects of the specified object type. Object-specific Add-in com-
mands follow the standard EViews object command syntax:
object_name.command(options) [args]
Suppose, for example, we have a global Generate time-series data Add-in with associated
command tsdgp. Since the Add-in is global, it will have a menu item in the main Add-ins
menu,

Moreover, the global command


tsdgp(diff="2", seed=100, meanconst="2", ar="0.1", ma="0.15",
varconst="0.8", arch = "0.15", garch="0.2 0.2") y

will run the Add-in program with the specified options.

Suppose, in addition, that we have two equation-specific Add-ins, Simple rolling regression
and Advanced rolling regression, with associated object-specific commands, roll and
advroll. If equation EQ1 is the active object, the main Add-ins menu will contain both the
global (Generate time series data) and the two equation-specific entries (Simple rolling
regression and Advanced rolling regression):
Using Add-ins—213

In contrast, the EQ1 equation object will have an object Add-ins menu contains only the
two object-specific entries:
214—Chapter 8.Using Add-ins

To run the simple rolling regression Add-in you may select either the main or the equation
menu Add-ins entries, or you may enter the equation object command:
eq1.roll

in the EViews command window.

If you wish to see the available Add-ins and their types, you may click on the Add-ins/Man-
age Add-ins... entry in the main menu to display the Add-ins management dialog. EViews
will display the list of installed Add-ins with a Type column showing the type associated
with each entry:
Add-ins Examples—215

Note that you may use the Add-in type drop-down to filter the display.

In this example, the Recshade (Add USA Recession Shading, ROLL (Simple Rolling Regres-
sion), and Advroll (Advanced Rolling Regression), Add-ins are all object-specific, while the
Tsdgp (Generate time series data) Add-in is global.

Add-ins Examples
To further illustrate the use of Add-ins, we examine two of the Add-ins currently available
for download from the EViews website. (To follow along with these examples, we recommend
that you first download and install the corresponding Add-in using the steps outlined in “Get-
ting Started with Add-ins” on page 207.)

Summarize Equation Results


Our first example is a global Add-in (EqTabs) that creates a table summarizing the results
from multiple equations. If you have not already downloaded and installed this Add-in, we
recommend that you do so now. We employ the workfile “Demo.WF1” (which may be
found in the examples subdirectory of your EViews installation directory.

To run the Add-in, go to the main EViews menu, and select Add-ins/Equation Output Table
(Summary form). EViews will display a dialog prompting you for the names of the equa-
tions you wish to summarize:
216—Chapter 8.Add-ins Examples

The default entry of “e*” is sufficient for this example since we want to summarize results
for the previously estimated equations EQ01 and EQ02. Click on OK to continue.

EViews will display a series of dialogs prompting you to specify the headers you wish to
include in the summary table, the information you wish to display, and the display format.
For example, the last dialog lets you choose the standard errors and t-statistics display for-
mats, along with the number of significant digits for coefficients and other statistics:

EViews will use the specified settings in constructing a table that summarizes the results
from all of the specified equations.
Add-ins Examples—217

You may also launch the Add-in from the command line or via batch execution of a program
file. Simply enter the user-defined command:
eqsumtab eq*

in the command line or include it in your batch program. The command instructs EViews to
run the program, displaying the set of dialogs prompting you for additional input, and con-
structing the table accordingly.

U.S. Recession Graph Shading


Our second example uses the graph-specific Add-in (RecShade) to add shading for periods of
U. S. recession (as determined by the National Bureau of Economic Research).

We start by opening the graph object GT in the “Macromod.WF1” workfile (which may be
found in the example files subdirectory of your EViews installation directory).
218—Chapter 8.Add-ins Examples

Next, click on the Proc/Add-ins menu item in the graph toolbar to display the Add-ins we
have installed that work with graph objects. In this case, there is only a single menu item
Add US Recession Shading:
Add-ins Examples—219

You may also access the active object menu items by clicking on the Add-ins entry in the
main EViews menu. When the graph object GT is the active object, the main Add-ins menu
shows both the global and graph specific menu items:

Selecting the Add US Recession Shading entry in either the main or graph object Add-ins
menu runs the Add-in program which adds shading to the existing graph:

For those who prefer to use a command, you may go to the command line and enter the
user-defined object command
gt.recshade

to apply the recession shading. This command may also be included in a program file for
batch execution.
220—Chapter 8.Managing Add-ins

Managing Add-ins
EViews offers a complete system for managing your Add-ins. To bring up the management
dialog, you should select Add-ins/Manage Add-ins... from the main EViews menu:

The management dialog is divided into two sections:


• The Registered Add-ins section is where you will perform most of the tasks of man-
aging your Add-ins (add, delete, edit, update, and reorder Add-in definitions, and
view the documentation file).
• The Default Add-ins directory section allows you to set the default directory for your
Add-ins.

Registered Add-ins
The top portion of the dialog shows settings for currently installed Add-ins, with each line
devoted to an Add-in.
Managing Add-ins—221

By default, all of the installed Add-ins will be displayed. You may use the Add-in-type drop-
down menu to filter the list, showing for example only global or only equation-specific Add-
ins.

The File name column shows the name (and possibly location) of the Add-in program, and
the Type column indicates whether the Add-in is global or object-specific. The Proc column
shows the command keyword associated with the Add-in (if any), while the Menu Text col-
umn shows the text used in the user-defined menu entries. The Version column show the
version number of the Add-in.

You may use the buttons and arrows on the right-hand side of the dialog to manage your
Add-ins:
• To add a new Add-in to the list, simply click on the Add button to display the Add/
Edit Program dialog. The Add/Edit Program dialog is described in detail in “Register-
ing an Add-in” on page 223.
• To delete an Add-in, simply click on the name in the Add-ins management dialog and
press the Remove button.
• The order in which your Add-ins appear in the menus may be controlled using the up
and down arrows. If you have many Add-ins, putting the most frequently used Add-
ins first in the list may simplify menu access (see “Menu Congestion” on page 226).
In addition, the order in which Add-ins appear can have important consequences in
the event that Add-ins duplicate command names (see “Command Masking” on
page 225).
• To edit the settings of an existing Add-in, select it from the list and chick on the Edit
button to display the Add/Edit Program dialog. The Add/Edit Program dialog is
described in detail in “Registering an Add-in” on page 223.
222—Chapter 8.Creating an Add-in

• To examine the documentation file associated with an Add-in, click on the name and
press the Docs button.
• To check whether the Add-in has an updated version available, and to install the
update if available, click on the Update button.

Note you may select multiple Add-ins at the same time and click on the Remove or Update
buttons to perform the specified operation. You may also right click anywhere on the list of
Add-ins and select Update All to check for updates on all of your Add-ins.

After modifying the desired settings, click on OK to accept any changes.

Default Add-ins Directory


The bottom portion of the Add-ins dialog shows the current default Add-ins directory. The
default directory is where an Add-in will search for supplementary files if explicit directory
locations are not provided. To change the default directory, click on the button on the right
and navigate to the desired directory, or simply enter the desired folder name. Click on OK
to accept the settings.

Creating an Add-in
You can use Add-ins developed by others without ever having to create one yourself. Indeed,
many users will never need to go beyond running Add-ins downloaded from the EViews
website or other repositories.

You may find, however, that creating your own Add-ins is both useful, if only to add a menu
item or assign a one-word command for running your favorite EViews program, and easy-to-
do.

Assuming that you already have an EViews program, creating an Add-in requires at most
two steps:
• Register the program as an Add-in. Registering an Add-in is the process of defining the
Add-in type and assigning menu entry and command keywords to an EViews pro-
gram.
• (optional) Create an Add-in package for distribution. Bundling your program files into
a self-installing package file and providing a program for automatically registering the
Add-in means that others can more easily incorporate your Add-in into their EViews
environment.

While only the first step is required, you should consider the optional step of creating a self-
installing Add-in package if you wish to distribute your Add-ins more widely.
Creating an Add-in—223

In the remainder of this section we describe the steps required to register an Add-in. In addi-
tion, we provide design tips and describe additional programming tools that will aid you in
writing sophisticated Add-in programs.

Registering an Add-in
The process of defining the Add-in type and assigning menu entry and command keywords
to an EViews program is termed registration. The Add-in registration process may also be
used to associate documentation with the Add-in.

To register an EViews program file as an new Add-in, click on the Add-ins/Manage Add-
ins... menu entry in the main EViews menu. The top portion of the management dialog
shows the list of currently registered Add-ins:

Click on the Add button to display a standard file Open dialog. Navigate to the program file
you wish to register and click on OK to continue.

EViews will display the Add/Edit Program dialog with various default settings.
224—Chapter 8.Creating an Add-in

The dialog allows you to specify a command keyword for the Add-in, to add menu items for
point-and-click access to the Add-in, and to attach documentation and descriptions.
• The Program file edit field in the dialog should be used to specify the program to be
used as an Add-in. You may enter the name of a file (with an absolute or Add-ins
directory relative path, if necessary) or you may click on the button to the right-hand
side of the edit field to navigate to the file.
• The Documentation file edit field allows you specify a PDF, Text, RTF, Microsoft
Word file, or URL containing documentation for the Add-in. Note that relative paths
are evaluated with respect to the directory of the Add-in program, not the default Add-
in directory.
• The Menu/Procedure type dropdown setting determines whether the program is a
global or an object specific Add-in. (Recall that global Add-ins are those designed to
work with multiple objects or object types, while object-specific Add-ins work with a
single object and object type.)
• If you check Assign as Command or Proc, EViews will add the specified single-word
command or proc keyword to the EViews language, so you may run the Add-in using
a global or object command. Names for the keyword must follow standard EViews
command naming convention. Global Add-ins should not be given the same name as
built-in EViews commands. (See “Command Masking” below, for additional discus-
sion.)
• If you check Include in Add-ins menu, EViews will add the specified Menu text to
the appropriate menus.
Creating an Add-in—225

• You may use the Brief description edit field to describe the purpose of the Add-in.
• You may enter a Version number for your Add-in and an Update URL indicating
where to find the update XML file (see “XML File Specification” on page 228).

In the example above, we instruct EViews to use the file “Rtf_out.PRG”, which is located in
the default Add-ins directory, as an Add-in program. We indicate that the program is a global
Add-in that may be run from the main EViews menu by selecting the Add-ins menu item
Output to RTF or by issuing the command rtf_out. There is no documentation file.

Add-ins Design Issues


For the most part, defining commands and menu items for an Add-ins is straightforward.
There are, however, a few issues that you should bear in mind when designing your Add-in.

Command Masking
Allowing you to define user-specified Add-in command names opens up the possibility that
an Add-in will be assigned the same command as an existing EViews command, or that mul-
tiple Add-in programs will be assigned the same name. Duplicate command names will gen-
erate an error or will lead to command masking where some of the instances will be
ignored.
• If you specify a global Add-in command name that is identical to an EViews command
or a previously defined global Add-in command, EViews will issue an error message,
and will display the Add/Edit Program dialog so you can provide a different name.
EViews will not, for example, permit you to register an Add-in with the global com-
mand copy since this conflicts with the built-in command.
• EViews will not generate an error message if you provide an object-specific command
name that is identical to a built-in command, but the EViews command will mask the
user-defined command. EViews will, for example, permit you to register an equation
command with the name resid, but if you enter the equation command “eq01.resid”,
EViews will display the built-in resid view of equation EQ01, instead of running the
user-defined Add-in.
• If you specify an object-specific Add-in command name that is identical to another
object-specific command, EViews will not error. When multiple Add-ins are assigned
the same object-specific command, the first Add-in listed in the list of registered Add-
ins will be used and the remainder will be masked. To eliminate masking, you must
edit the conflicting Add-in command definitions. If you wish to retain the same com-
mand name for multiple Add-ins, you should use the Add-ins management dialog to
reorder the Add-ins list so that the desired Add-in has priority (“Managing Add-ins”
on page 220).
226—Chapter 8.Creating an Add-in

We emphasize that masking only occurs within like Add-ins. You may have a global, series,
and group Add-in that each use the same command without experience masking, but two
global Add-ins or two series Add-ins with the same name will lead to masking.

Menu Congestion
While you may define as many Add-in menu items as you like, EViews does place limits on
the number of menu items that may be displayed by default. If you have more than 10 global
menu entries or more than 10 object-specific menus of a given type, the corresponding
menus will display the first 10 entries, along with an 11th menu entry, More... Clicking on
More... displays a listbox showing the full set of entries. In such circumstances, we recom-
mend that you reorder your Add-ins so that the most used Add-ins are given priority.

Multiple Object Add-ins


You may wish to use a single program file to define Add-ins for several object types. Since it
is not possible to use a single Add-in entry to define multiple object-specific types, you must
create separate entries for each object-type which point to the single program file. For each
relevant object type, select Add-ins/Manage Add-ins... from the main EViews menu, then
navigate to and select the program file. Use the Add/Edit Program dialog to define the
object-specific entry.

Creating an Add-in Package


If you are developing Add-ins for use by others, we recommend that you create a self-install-
ing package so that users may easily incorporate your Add-ins in their EViews environment.
You can then host your package on a company intranet or perhaps submit your package to
be hosted on the EViews.com website for wide distribution.

The process of creating an Add-in package is straightforward, requiring at most two steps:
• (optional) Create a table of contents (TOC) information file and installer program file.
• Create a self-extracting Add-in package file containing the program and support files
(including the TOC and installer program file, if available).

The second step, creating the self-extracting package, is trivial. Simply create a standard ZIP
archive file containing all of the files for your Add-in, then rename the ZIP file so that it has
the extension “AIPZ”. You now have an self-extracting Add-in package file.

Opening a self-extracting package file, either automatically by a browser after completing


the download, by double clicking on the file, or by dropping it onto EViews, will prompt you
to unpack and copy the files to the location of your choice.

The Add-in will not, however, automatically be installed and registered unless you include a
table of contents (TOC) information file and installer program along with your program files.
Creating the TOC and installer program files takes only a few minutes and allows you to
Creating an Add-in—227

automate the Add-in installation and allow for automatic updating of your Add-in as you
provide newer versions. We strongly recommend that package distributors take the time to
create these files as described below.

Table of Contents
First, you should create a table-of-contents file named “Toc.INI” for inclusion in your pack-
age. The TOC file should contain setup information which describes the directory in which
the Add-in files should be installed, and if appropriate, the name of an EViews installer pro-
gram for registering the Add-in. The format of the TOC file is:
[package]
installer = <name of installer file>
folder = <name of folder to create>

A TOC file should always begin with the line “[package]”, followed by lines which give the
directory and installer information.

The installer keyword is used to indicate the name of the EViews program file, if one
exists, that should be run to register the Add-in (see “Installer Program” on page 228). If, for
example, a registration program file named “Recession shade install.PRG” is included in
your package, you should include the line
installer = recession shade install.prg

If you include this line in your TOC, EViews will automatically run the installer program
when it opens the AIPZ package. If you do not wish to provide an installer program, you
should include the line “installer=none” in the TOC file.

The folder keyword may be used to indicate a subfolder of the default Add-ins directory
into which you will extract the packaged files. Thus,
folder = RecShade

tells EViews to extract the contents of the AIPZ file into the “RecShade” folder of the Add-ins
directory. If no folder is specified, the name of the AIPZ file will be used as the target folder
name. Additionally, you may use the special folder name “<addins>” to indicate that the
contents of the AIPZ archive should be placed in the main Add-ins directory. (Note, how-
ever, that only folders in an AIPZ archive may be written to the main Add-ins directory in
this fashion; individual files in AIPZ files must be written into subdirectories.

We emphasize that creating a TOC file and providing an installer program are not required.
In the absence of a TOC file or an installer= specification, EViews will, after unpacking
the AIPZ files, simply display a message reminding the user that the installed programs may
be registered manually using the Add-ins management dialog.
228—Chapter 8.Creating an Add-in

Nevertheless, we strongly recommend that package distributors provide both a TOC file and
installation program to facilitate use of their Add-ins. Packages hosted on the EViews web-
site must include both a TOC and an installer.

Installer Program
Next, you should create a simple EViews program that uses the addin (p. 365) command to
register the Add-in with appropriate type, menu, and command settings. Note that the TOC
file installer= specification should point to this installer program.

For example, the graph-specific Add-in described in “U.S. Recession Graph Shading” on
page 217 may be registered by including the following command in a program file:
addin(type="graph", menu="Add USA Recession Shading",
proc="recshade", docs=".\recession shade.txt", desc="Applies US
recession shading to a graph object.") ./recshade.prg

The options in this example should be self-explanatory. The command registers the program
“./recshade.PRG” as a graph-specific Add-in with menu item “Add USA Recession Shading”,
command name “recshade”, and description text “Applied US Recession shading to a graph
object”.

See addin (p. 365) for details and a complete list of options. Use of the following addin
options is highly recommended:

Documentation
We recommend that you provide documentation for your Add-in, and use the “docs=”
option to point to the documentation file.

Documentation could be anything from a simple text file with some syntax hints, to a
lengthy PDF document that describes the Add-in features in detail.

Version
EViews allows Add-ins to have a version number which allows the users of your Add-in to
use automatic updating to ensure they have the latest version of the Add-in. When a user
uses the Update button on the Manage Add-ins dialog to check for Add-in updates, EViews
will compare the hosted version number with the currently registered version number and
download the latest version if necessary.

You may use the “version=” option to specify the version number. If omitted, EViews will
assume that the Add-in version number is 1.0.

XML File Specification


One of the most useful Add-ins management features is the ability of users to automatically
update their installed Add-ins as newer versions become available. To support this feature,
Creating an Add-in—229

EViews must know where to look to determine the most recent version of the Add-in and
where to download any updates.

This information is communicated in an XML file, typically located on the Add-ins package
hosting site. If you will be hosting this file, you should use the addin option “url=” to spec-
ify the URL for the XML file. If this option is not supplied, EViews will look for the XML file
on EViews.com.

The XML file should contain one or more item definitions, where each item contains infor-
mation on a specific Add-in. An item definition is contained in the lines between an <item>
and </item> tag. An example of the full specification of an item is as follows:
<item>
<title>BMA</title>
<path>bma\bma.prg</path>
<path>bma\bmamlogit.prg</path>
<version>1.0</version>
<description>Computes different Bayesian Model Averaging methods
including LM, GLM and Multinomial Logit models.</description>
<link>http://eviews.com/Addins/BMA.aipz</link>
<pubDate>13 Mar 2012</pubDate>
</item>

Note that the only required specifications are the <title> and <link>.

The <path> specification is used to identify the paths and file names of the main program
files used by the Add-in, with the path location specified relative to the Add-ins directory.
Automatic updating will update these files when a newer Add-in version is available. If
<path> is not specified, EViews will use the <title> specification to determine the rele-
vant Add-in proc name, and use registration information for the proc name to determine the
files to update.

When an add-in package has multiple main program files, a <path> statement is required.
You should list each file using a separate <path> entry. In the example above, the BMA Add-
in has two program files, called “bma.PRG”, and “bmalogit.PRG” that are associated with
procs. EViews will update all of the files associated with these procs when updating the
Add-in.

The <version> is used to specify the current Add-in version number. When the user checks
for updates, EViews will download the updated version if the version number they have cur-
rently installed is lower than the one given in the <version> tag.

Finally, the <link> specification contains the URL (or network file location) of the AIPZ file
containing the Add-in. This is the location from which EViews will download the updated
Add-in package should the user request an update.
230—Chapter 8.Add-ins Design Support

The <description> and <pubDate> specifications should be self-explanatory.

Add-ins Design Support


EViews offers several programming language features that will aid you in developing and
working with Add-ins.

Add-ins Registration Command


The addin command may be used to register an EViews program file as an Add-in. You may
use the command to specify the Add-in file, Add-in type, menu text, user-defined command
name, description, version number, documentation file, XML file, etc.

See addin (p. 365) for details.

The Active Object Keyword


“_this” Keyword
Central to the construction of an object-specific Add-in program is the ability to reference
the object on which the program should act. If, for example, you wish to write an Add-in
that computes a statistic based on the data in a series object, you must have a convenient
method of referring to the series.

Accordingly, EViews provides an object placeholder keyword, _this, which refers to the
currently active object upon which a program may operate. Typically the use of _this in an
EViews program indicates that it has been designed to work with a single object.

There are three ways in which the identity of the _this object may be set:
• _this refers to the active object whose window was last active in the workfile; when
used in a program, _this refers to the active object at the time the program was run.
• executing an Add-in using the object-command syntax, obj_name.proc, sets _this to
obj_name.
• _this can be set to a specific object using the “this=” option in an exec or run com-
mand.

While the above description is a bit abstract, a simple example should illustrate the concepts
that lay behind the three methods. Suppose we have the trivial (silly) program
“Myline.PRG” which consists of the command:
_this.line

First, if we register this program as a global Add-in with menu item text “Show line”, we can
display a line graph of a series or group object by opening the series or group and selecting
Show line from the Add-in menu. From the program’s point of view, the _this object is
Add-ins Design Support—231

simply the opened series or group whose menu we are using (the last one active in the
workfile).

Alternately, if we had registered the program as a series-specific Add-in with proc name
“myl”, the command:
ser01.myl

identifies SER01 as the _this object, so that the object used by the Add-in will be the series
SER01, regardless of which object is active in the workfile.

Lastly, you may specify _this explicitly when using the exec or run command to run the
program by including the “this=” option to identify an object by name. The command:
exec(this=ser01) myline.prg

explicitly specifies SER01 as the _this object.

Custom Object Output


EViews allows you to display the contents of a table, graph, or spool object in the window of
another object. This feature will undoubtedly most often be used to mimic the behavior of
EViews views and procedures in Add-ins programs.

Suppose, for example, that your Add-in program performs some calculations and constructs
an output table TABLE_OUT. You may instruct EViews to display the contents of
TABLE_OUT in the object OBJECT_01 using the display command:
object_01.display table_out

Thus, a useful approach to constructing an object-specific Add-in involves creating a pro-


gram of the form:
[use _this to perform various calculations]
[create an output table or graph, say the table TABLE01]
’ put the output in the _this window
_this.display table01
delete table01

Note that we delete the TABLE01 after we put it in the window of _this. (You may instead
wish to employ local subroutine to enable automatic cleanup of the temporary table.)

If the above program is registered as a series-specific Add-in with the command “FOO”, then
you may run it by issuing the command
series01.foo

which will display the output in the SERIES01 window.


232—Chapter 8.Add-ins Design Support

The display object command is a documented view for each supported object. See for
example, Series::display (p. 779) in Object Reference.
Chapter 9. User Objects

As the name suggests, the EViews user object allows you to create your own object types
inside of EViews. A user object may be as simple as a storage container for other EViews
objects, or it may be a sophisticated new estimation object defined by multiple EViews pro-
grams, with views containing post-estimation tests and results, and procedures producing
output from the estimation results. Once defined, a user object is almost indistinguishable
from a built-in EViews object.

Defining a user object is quite easy—simply specify the types of data and objects stored
inside your object, and if desired, define a set of views and procedures that be accessed via
commands, menus and dialogs.

Even if you do not go to the trouble of creating your own objects, you may take advantage of
this powerful tool by using user objects downloaded from the S&P EViews website or
obtained from third-parties.

What is a User Object?


An EViews user object is a custom object that can contain data and objects and may offer
views and procedures. In its simplest form, a user object is a storage container for EViews
objects. More sophisticated user objects also provide views and procs that allow you to run
EViews programs to perform various tasks and display results. These latter objects work
almost identically to built-in EViews objects such as a series or equation.

In the discussion to follow it will be important to distinguish between user objects that are
unregistered or registered:
• Unregistered user objects are simple container objects which require virtually no
effort to create.
• Registered user objects are more powerful than unregistered user objects. Registering
a user object class is the process of describing what happens each time a new
instance of the user object is created, and defining data and a set of views and procs
available to the user object class.

A relatively complex registered user object might be a complete econometric estimator. Each
time a new instance of the estimator object is created, it could specify and perform estima-
tion, saving results inside the user object in the form of data objects such as coefficient vec-
tors and covariance matrices. The object could also offer views such as coefficient tests and
procs to perform forecasting. And like an EViews equation object, you may have multiple
instances of this estimator in the workfile, each corresponding to a different set of estimates.
234—Chapter 9.Unregistered User Objects

We note that a registered user object need not be particularly complex. For example, you
could have a simple user object called “RESULTS” that contains a collection of graphs,
tables, and estimation objects obtained from a particular form of analysis. You could define
simple views for your user object that display the stored tables or graphs, and define procs
that let you extract those tables or graphs into new EViews objects. Registering the object
allows you to have multiple results objects in your workfile.

Unregistered User Objects


To create a new, unregistered user object, select Object/New Object in the main EViews
menu.

Scroll down and select UserObj, enter a name for the object in the workfile (in this example,
MYOBJ), and click on OK. Alternately, you may enter the generic user object declaration
command
userobj myobj

to create a user object named MYOBJ in the workfile.


Unregistered User Objects—235

Notice that MYOBJ has a black icon. A user object created in this fashion is empty, with no
user-defined views or procedures. Double-clicking on MYOBJ opens the object and displays
its contents:

As you can see, the object is empty. Clicking on the View menu of the object shows only a
single Label entry. The Proc menu is completely empty.

An empty, unregistered userobj is not particularly interesting. You may, however, use the
object as a container for EViews matrix objects (including scalars), string objects, estimation
objects, and view objects (graphs, tables, spools):
• The add (p. 1123) and drop (p. 1127) procs may be used to populate the user object
and the extract (p. 1128) proc may be employed to extract objects into the workfile.
• You may use user object data members to provide information about the contents of
the object: the @hasmember(obname) member function can be used to determine
whether obname exists inside the user object, while @members returns a space delim-
ited string listing all objects in the user object.
236—Chapter 9.Registered User Objects

See “User Object Programming Support” on page 257 for details.

The following program offers a simple example showing the use of these commands:
userobj myobj
myobj.add mygraph
myobj.add mytable
%list = myobj.@members
myobj.drop mygraph
myobj.extract mytable mynewtable

The first line creates a new, empty, user object called “MYOBJ”. The second and third lines
copy the workfile objects “MYGRAPH” and “MYTABLE” into MYOBJ. The fourth line creates
a string variable whose contents are “mygraph mytable”. The fifth line removes MYGRAPH
from MYOBJ, and the final line copies MYTABLE back into the workfile under the name
MYNEWTABLE.

Registered User Objects


While simple, unregistered user objects may only be employed as storage containers, regis-
tering a user object class creates a more powerful working environment. Note that we used
the term user object class, reflecting the fact that when you register a user object, you are not
simply declaring a single object but rather are defining the general characteristics of a type
of object.

Registering a user object class allows you to have multiple objects of a given type in your
workfile, each of which has its own data. Additionally, registering allows you, if desired, to
define views and procs that can be used by any object of that class. These views and procs
will execute a set of EViews programs that you specify as part of the registration procedure.

While not difficult, creating a registered user object class is a bit more involved than creating
an unregistered user object. Details are provided in “Defining a Registered User Object
Class” on page 251.

You may, of course, download and register user object classes created by others. Since work-
ing with example user objects provides good introduction to this powerful tool, we begin by
discussing the steps required to download an object from the EViews website.

Downloading a Registered User Object


To download and install object class definitions from the EViews website, simply select Add-
ins/Download User Objects...from the main EViews menu.
Registered User Objects—237

EViews opens the User objects management dialog opened to the Available tab, which
shows a list of the user objects classes (in this case ResStore, Roll, and BiProbit), that are
available for download along with the date they were published, their version number, and
their status (blank for un-installed, installed, or installed but out of date):
238—Chapter 9.Registered User Objects

Selecting an entry displays a description of what the user object does below the listbox.
Clicking on the Install button downloads the selected user object and prompts you to install
the package on your the local computer. (Alternately, you may click on the Website button
and follow the navigation links to the user objects page. Download the appropriate file to
your computer then open it using EViews by double-clicking on the file or dropping it onto
the EViews application window or the application icon.)

The first step in installa-


tion is to unpack and
copy the files to your
computer. By default,
EViews will put the files
in a sub-folder of your
default directory (see
“Default User Objects
Directory” on page 251) but you may choose an alternate location if desired (you may use
the “...” button on the right-hand side to navigate to a specific directory). Click on OK to
proceed.

To unpack the files without using EViews, simply change the download file extension from
“AIPZ” to “ZIP” and use your favorite ZIP file tools to extract the contents into the desired
directory.

Next, EViews will prompt you to run and installation program that is included in the user
object package.

If you click on No in response to the installation prompt, EViews will finish the automatic
install procedure without running the installation program and registering the userobj. You
may later examine the installation program prior to running it as you would any other
EViews program, or you may manually register your object as described in “Registering a
User Object Class” on page 253.

Click on Yes to finish the installation and registration. If there are conflicts with existing
directory names or existing user objects, EViews will warn you before proceeding.

After completion of the automatic installation procedure, EViews will report the status of the
installation:
Examples—239

We note that installing and running an EViews program file provided by an unknown indi-
vidual has risks. Accordingly, we recommend that care be taken when installing packages
from non-trusted sites.

All of the packages provided on the EViews website have been examined to ensure that they
do not include potentially harmful commands.

Working with Registered User Objects


Once you have registered your user object you may work with it much as you would any
built-in EViews object.

You can create a new instance of the object using the Object/New Object... main menu
item, or by declaring it on the command line using the name of the object and any relevant
options or arguments:
userobj_class_name(options) my_objname [args]

You may use the defined views and procs of the object using the object View or Proc menu,
or via the command line using the standard syntax:
userobj_name.view_name(options) [args]
userobj_name.proc_name(options) [args]

The user object data member @-functions may be accessed using the syntax:
[result_type] result = userobj_name.@datamember_name[(arg)]

Examples
To illustrate the use of registered user objects, we examine two of the EViews user objects
that are currently available for download from our website. (To follow along with these
examples, we recommend that you first download and install the corresponding user object
using the steps outlined in “Downloading a Registered User Object” on page 236.)

The first example uses a simple container user object (of type ResStore) that allows you to
add, extract, and display graphs, tables and estimation objects. The second example per-
forms rolling regression estimation using the Roll user object.
240—Chapter 9.Examples

Simple Container Object (ResStore)


This first example uses the ResStore user object to create a storage container for objects from
our workfile. This is a bare bones registered object that nonetheless shows the basic features
of registered user objects.

We use the workfile “Demo.WF1” (which may be found in the example files subdirectory of
your EViews installation directory) and assume that you have already installed the ResStore
object class.

You may create a new ResStore object by clicking on Object/New Object... and then select-
ing resstore in the list of object types.

Notice that while the built-in EViews objects are listed alphabetically, the two user objects
(ResStore and Roll) are simply placed at the bottom of the listbox. Select resstore and spec-
ify the name STOREDOBJECT for our new object. Click on OK to create the object. Alter-
nately, enter the command
resstore storedobject

in the EViews command line and hit ENTER.

As part of its construction, the ResStore object will display a dialog asking you to enter the
names of the workfile objects you would like to store:
Examples—241

You may enter the names of any matrix objects (including scalars), strings objects, estima-
tion objects, or view objects (graphs, tables, spools).

Note that there is a check-box that lets you specify whether to remove the objects from the
workfile after storing them. You should selection this option if you wish to move, rather than
copy, the specified objects into the ResStore.

Once you hit OK, a new ResStore object named STOREDOBJECT will be added to your
workfile. If you open up the ResStore object, a spool view display of all objects currently
stored is shown:

You may use the View menu to access the defined views for this type of object which allow
you to show various subset types of the objects in the container:
242—Chapter 9.Examples

Similarly, the Proc menu lists procs which allow you to add, remove, and extract objects
from the storage container:

As with other EViews objects, you may use the command language to work with the ResS-
tore object. For example the defined view command,
storedobject.graphs

displays all of the graph objects in the object


storedobject.extractobjects

extracts all of the objects from STOREDOBJECT into the workfile.

The command
Examples—243

string storednames = storedobject.@members

saves a list of the stored object names in the string object STOREDNAMES.

Rolling Regression Estimation Object (Roll)


Our second example uses the Roll user object to estimate rolling regressions. We again use
the workfile “Demo.WF1”, and we assume that you have already installed the Roll object
class.

You can create a new Roll object by clicking on Object/New Object... and then selecting roll
in the list of object types, or by entering the roll command followed by the name of a new
object in the command line:
roll myroll

As part of its creation, the Roll object will display a series of dialogs prompting you to pro-
vide information on how the object should be constructed. First, you will be asked whether
to create the new object using the specification from an existing equation or by specifying an
equation manually:

Since we will use one of the previously estimated equations in our workfile as the basis of
our rolling regression, click on OK to accept the default.

Next, you will be asked to select your base equation and to specify the basic type of rolling
regressions you wish to perform:

To obtain recursive estimates based on equation EQ01 choose EQ01 in the drop-down menu
and select Anchored at start. Click on OK to continue.

Lastly, you will be prompted to provide sample information and a step size:
244—Chapter 9.Examples

Click on OK to create the Roll object using the specified settings.

(Note that if you had chosen Manual equation specification in the first dialog or Fixed
window estimation in the second dialog, the subsequent dialogs would provide a different
set of options).

EViews estimates the rolling regression and, like built-in estimation objects, displays basic
estimation information in the object window:
Examples—245

Roll: MYROLL
Roll type: Anchored at start
Specification: EQ01
Estimation command: ROLL(AS,STEP=1,ANCHOR=1953Q1) MYROLL
@ EQ01

Anchor point: 1953Q1


Number of subsamples: 160
Number of coefficients: 4
Step size: 1

Full sample estimation results:

Dependent Variable: LOG(M1)


Method: Least Squares
Date: 01/31/13 Time: 10:19
Sample (adjusted): 1952Q2 1992Q4
Included observations: 163 after adjustments

Variable Coefficient Std. Error t-Statistic Prob.

C 1.312383 0.032199 40.75850 0.0000


LOG(GDP) 0.772035 0.006537 118.1092 0.0000
RS -0.020686 0.002516 -8.221196 0.0000
DLOG(PR) -2.572204 0.942556 -2.728967 0.0071

R-squared 0.993274 Mean dependent var 5.692279


Adjusted R-squared 0.993147 S.D. dependent var 0.670253
S.E. of regression 0.055485 Akaike info criterion -2.921176
Sum squared resid 0.489494 Schwarz criterion -2.845256
Log likelihood 242.0759 Hannan-Quinn criter. -2.890354
F-statistic 7826.904 Durbin-Watson stat 0.140967
Prob(F-statistic) 0.000000

These basic results may be viewed at any time by selecting View/Summary in the object
view menu or by entering the object command
myroll.summary

in the command line.

Next, consider the custom views that have been defined for this object. In addition to the
summary view, you may display information on the coefficient statistics, residual statistics,
likelihood statistics, members of the object, and the standard label information view for the
Roll object:
246—Chapter 9.Examples

Clicking on View/View rolling coefficient statistics... display a dialog prompting you to


select the coefficients and statistics you wish to display. By default, the object will display
the coefficient estimates for all of the coefficients in the regression:

Click on OK to accept the default values and to display a graph of the results in the object
window:
Examples—247

Equivalently, you could have issued the command:


myroll.rollcoefs c log(gdp) rs dlog(pr)

in the command line.

Note that you could have specified a different statistic in the dialog or add the “stat=”
option to the command to display a different coefficient statistic. For example, selecting P-
values in the dialog or entering,
myroll.rollcoefs(stat=pvals) c log(gdp) rs dlog(pr)

displays the coefficient t-statistic p-values:


248—Chapter 9.Examples

Similarly, you may click on the Proc menu to display a list of the user defined procs:

The first two entries re-initialize the Roll object using the dialogs we first encountered when
creating MYROLL. The next three menu entries extract results into the workfile. For exam-
ple, clicking on Extract rolling residual statistics... opens a dialog prompting you to iden-
tify the results you wish to extract along with the destination:
Managing User Object Classes—249

2
Clicking on OK t saves the R statistics in the workfile in the series ROLL_R2. The com-
mand
myroll.extractresidstat(stat=r2s) roll_r2

performs an equivalent operation.

It is worth noting that behind-the-scenes in this object is a set of user programs that use
standard EViews programming tools to display dialogs, perform computations, and display
and extract results.

Managing User Object Classes


To manage your user object definitions, select Add-ins/Manage User Objects... from the
main EViews menu.
250—Chapter 9.Managing User Object Classes

EViews will display the User objects management dialog opened to the Installed tab:

The top portion of the dialog shows settings for currently registered user object classes. The
Name column shows the name of the class, the Definition file column displays the location
Defining a Registered User Object Class—251

and file name of the definition “.INI” file for the class (see “Creating an Object Definition
File” on page 252), and the Version column shows the version number of the user object
class.

Note that you may click on the column headers in the list to sort the list by the contents of
column.

You may use the buttons on the right-hand side of the dialog to manage your classes:
• To add a new user object to the list, simply click on the Add button to display the
Add/Edit User Object dialog. The dialog settings are described in “Registering a User
Object Class” on page 253.
• To delete a class, simply click on the name in the Add-ins management dialog and
press the Remove button.
• To edit the settings of an existing user object class, select it from the list and click on
the Edit button to display the Add/Edit User Object dialog. The dialog settings are
described in “Registering a User Object Class” on page 253.
• To open and edit the INI definition file for the user object class, select it from the list
and click on the Open button.
• To examine the documentation file associated with a class, click on the name and
press the Docs button.
• To check whether the userobj class has an updated version available, and to install the
update if available, click on the Update button. Note you may select multiple classes
at the same time and click the Update button to update the set. You may also right
click anywhere on the list of user object classes and select Update All to update all of
your classes.

Default User Objects Directory


The bottom portion of the Installed tab shows the default user objects directory. The default
directory is where user objects will be installed and where the user object programs will
search for supplementary files if explicit directory locations are not provided. To change the
default directory, click on the button on the right and navigate to the desired directory, or
simply enter the desired folder name. Click on OK to accept the settings.

Defining a Registered User Object Class


To define a registered user object class, you must provide information on how to construct
(create) an instance of the object. While the constructor information is all that is required,
you may optionally specify menu items and custom command names for views and procs
that will execute EViews programs.
252—Chapter 9.Defining a Registered User Object Class

We may divide the registration procedure into two distinct steps:


• Create an object definition file which includes constructor, view, and proc definitions.
• Register the object definition file with EViews.

This discussion assumes that you have already written programs to initialize your object and
possibly to display views and execute procs. These programs will be standard EViews pro-
grams that use ordinary EViews commands. There are, however, several programming fea-
tures which are designed specifically for user object (and Add-in) program development that
you should find useful. See “Add-ins Design Support” on page 230 in the Command and Pro-
gramming Reference.

Creating an Object Definition File


The object definition file is a simple text file with a “INI” extension. This file describes how
to construct the custom object using an EViews program and optionally provides menu
items and custom command names for views and procs that will execute EViews programs.

There are three sections in the file, corresponding to the constructor, the views, and the
procs of the object.

The first section of the definition file should start with a line consisting of the text “[con-
structor]” (without the quotes). The line immediately following should contain the path and
name of an EViews program file that will be used as the constructor. The constructor pro-
gram file describes how the object should be initialized, or constructed, when you create a
new instance using the Object/New Object... menu item or the command line.

The second section contains the view definition specifications. This section should start
with a line consisting of the keyword “[views]”. Each line following this keyword will define
a view for the user object. Each view definition line should consist of the menu text, fol-
lowed by a comma, a custom command name for the view, a comma, the path and name of
the program file to be run when the view is selected from the menu or run from the com-
mand line.

The third section contains the proc definition specifications. It follows the same format as
the views section, but begins with “[procs]” rather than “[views]”.

Note that when providing the path of the programs in your definitions, the “.\” shortcut can
be used to denote the folder containing the definition INI file.

For example, the following is the definition file for the ResStore user object:
[constructor]
".\resstore construct.prg"
[views]
"View stored objects", objects, ".\viewall.prg"
Defining a Registered User Object Class—253

"View stored equations", equations, ".\viewequations.prg"


"View stored graphs", graphs, ".\viewgraphs.prg"
"view stored tables", tables, ".\viewtables.prg"
[procs]
"Extract objects from store", extractobjects, ".\extract
objects.prg"
"Add objects to store", addobjects, ".\resstore construct.prg"
"Remove objects from store", dropobjects, ".\remove objects.prg"

The ResStore user object use a constructor program called “resstore construct.PRG” which is
called when you create a new ResStore object from the dialogs or command line.

There are four view menu items, each associated with a different EViews program. The first
view definition tells EViews that it should create a view menu item View stored objects and
object command objects, and associate both with the EViews program “viewall.PRG”
(which is located in the ResStore directory). This definition means that selecting View/View
stored objects from the object menu, or entering the object command
my_object.objects

will run the “viewall.PRG” program which displays all of the stored objects in MY_OBJECT.

Similarly, there are three proc menu items. Selecting Proc/Remove objects from store or
issuing the command
my_object.dropobjects

runs the “remove objects.PRG” program which displays a dialog prompting you for the
name of the objects to remove from MY_OBJECT.

Registering a User Object Class


To register a new user object class, select Add-ins/Manage User Objects... from the main
EViews menu to display the User objects management dialog, then click on the Add button
to display the Add/Edit Program dialog.
254—Chapter 9.Defining a Registered User Object Class

The dialog allows you to provide a name for the user object class, to specify the INI file,
attach a documentation file, and provide various object attributes:
• The Object name edit field should be used to specify the user object class name. Note
that if you provide the name of a built-in EViews object, the EViews built-in object
will take precedence.
• The Definition file edit field must be used to enter the name and path of the INI defi-
nition file. Note you may press the “...” button to navigate to and select the file.
• The Documentation file edit field allows you specify a PDF, Text, RTF, Microsoft
Word file, or URL containing documentation for the user object class. (Note that rela-
tive paths are evaluated with respect to the directory of the INI file, not the default
user object directory.)
• You may use the Brief description edit field to describe the purpose of the User
Object.
• You may enter a Version number for your user object and an Update URL indicating
where to find the update XML file (see “XML File Specification” on page 256).

You must provide an object name and a definition file to register your object. The remaining
information is recommended, but not required.

Creating a User Object Package


In “Defining a Registered User Object Class” on page 251 we showed how you can use
EViews program files and an object definition file to register a new user object class for per-
sonal use.

If you wish to distribute your custom object to others, we highly recommend that you create
a user object package. Packaging the user object allows you to bundle all of the files for dis-
Defining a Registered User Object Class—255

tribution and, if you provide an installer program, offers automatic installation of the object
by dragging-and-dropping the package onto EViews or double clicking on the file.

The process of creating a user object package is virtually identical to packaging of an EViews
Add-in, with a few minor exceptions. We summarize briefly the main steps. Related discus-
sion may be found in.

Creating the Self-installing Package


The process of creating a user object package is straightforward, requiring only two steps:
• (optional) Create a table of contents (TOC) information file and installer program file
to allow for automatic registration and updating of the Add-in.
• Create a self-extracting user object package file containing the object definition file
and any support files (including the TOC and installer program file, if available).

To create the self-extractive file simply create a standard ZIP archive file containing all of the
files for your user object, then rename the ZIP file so that it has the extension “UOPZ”.
Opening such an file, automatically after completing the download, by double clicking on
the file, or by dropping it onto EViews, will begin the automatic installation procedure.

The user object will not, however be automatically installed and registered unless you
include a table of contents (TOC) information file and installer program along with your pro-
gram files. Creating the TOC and installer program files takes only a few minutes and allows
you to support automatic registration and updating of the user object. We strongly recom-
mend that package distributors take the time to create these files as described below.

Table of Contents
Next, you should create a table-of-contents file named “Toc.INI”. The TOC file should con-
tain setup information for the user object which describes the directory in which it should
be installed, and the name of the EViews program, if any, that should be run to register the
user object files. The format of the TOC file is:
[package]
installer = <name of installer file>
folder = <name of folder to create>

A TOC file should always begin with the line “[package]”. The “installer” keyword is used to
indicate the name of the EViews program file that should be run to register the user object.
If, for example, a registration file named “Roll install.PRG” is included in your package, you
should include the line
installer = roll install.prg

The “folder” keyword may be used to indicate the subfolder of the default user object direc-
tory into which you wish to extract the package files. Thus,
256—Chapter 9.Defining a Registered User Object Class

folder = Roll

tells EViews to extract the contents of the UOPZ file into the “Roll” folder of the User Object
directory. If no folder is specified, the basename of the UOPZ file will be used as the target
folder name.

Installer Program
If you wish to facilitate automatic registration of the user object class, you should create a
simple EViews “.PRG” program that uses the adduo command to register the User Object
class. For example, the rolling regression user object described in “Rolling Regression Esti-
mation Object (Roll)” on page 243 may be registered by including the command
adduo(name="roll", version="1.0", desc="Rolling regression
object") ./rolldef.ini

in a program file, and including a reference to this file in the package table-of-contents.

Documentation
We recommend that you provide documentation for your user object, and use the “docs=”
option to point to the documentation file. Providing some documentation for the command
line methods of initializing the object and accessing views and procs is especially important.
Documentation could be anything from a simple text file with some syntax hints, to a
lengthy PDF document that describes the user object features in detail.

Version
You may specify an version number for your user object. Version numbers allow users to use
automatic updating to ensure they have the latest version of the object class definition files.
When a user uses the Update button on the Manage User Objects dialog to check for
updates, EViews will compare the hosted version number with the currently registered ver-
sion number and download the latest version if newer.

You may use the “version=” option to specify the version number. If omitted, EViews will
assume that the user object version number is 1.0.

XML File Specification


One of the most useful user object management features is the ability of users to automati-
cally update their installed user object as newer versions become available. To support this
feature, EViews must know where to look to determine the most recent version of the user
object and where to download any updates.

(Note that this specification is identical to the file specification for Add-ins and the material
below is virtually identical to the discussion for Add-ins.)

This information is communicated in an XML file, typically located on the Add-ins package
hosting site. If you will be hosting this file, you should use the adduo option “url=” to spec-
User Object Programming Support—257

ify the URL for the XML file. If this option is not supplied, EViews will look for the XML file
on EViews.com.

The XML file should contain one or more item definitions, where each item is a set of infor-
mation on a specific user object. The item definition is contained in the lines between an
<item> and </item> tag. The full specification of an item is as follows:
<item>
<title>Roll</title>
<version>1.0</version>
<description>User Object for performing rolling regression.</
description>
<link>http://eviews.com/Addins/Roll.uopz</link>
<pubDate>14 Dec 2012</pubDate>
</item>

The only required specifications are the <title> and <link>.

The <version> is used to specify the current user object version number. When the user
checks for updates, EViews will download the user object if the version number they have
currently installed is lower than the one given in the <version> tag.

The <link> specification contains the URL (or network file location) of the UOPZ file con-
taining the user object package. This is the location from which EViews will download the
updated Add-in package should the user request an update.

The <description> and <pubDate> specifications should be self-explanatory.

User Object Programming Support


EViews offers several programming language features that will aid you in creating, register-
ing and working with user objects.

Note that there is additional programming language support for creating the programs that
will be used to define your user object. These features are described in “Add-ins Design Sup-
port” on page 230.

Declaration
The userobj command is used to create a new, unregistered user object as in
userobj myobject

where myobject is the name of the object to be created. A userobj created using this com-
mand will be empty, and will have no constructor or defined views and procs defined.
258—Chapter 9.User Object Programming Support

To declare a registered user object, you will use the name of the class followed by the name
of the object:
userobj_class_name(options) myobject [args]

Depending on how the user object is designed, the declaration program may use options and
additional arguments args when running the constructor program.

See Userobj::userobj (p. 1131).

Registration
The adduo command may be used to register a user object, as in
adduo(name="roll", version="1.0", desc="Rolling regression
object") ./rolldef.ini

You may use the command to specify the object definition file, path, description, version
number, documentation file, XML file, etc.

See adduo (p. 367) for details.

View and Procs


Each type of user object will have its own views and procs:
• All user objects provide a small number of generic built-in views and procs. For exam-
ple, the standard EViews label view for viewing and modifying the label contents
and the display view for showing output in the object window are supported.
• All user objects support the add and drop procs which may be used to populate the
user object, and the extract proc may be employed to extract objects into the work-
file.
• In addition, registered user objects may provide custom views and procs. You should
view the specific user object documentation file for details.

As with any EViews object, you may access the views and procs of the user object using the
object View or Proc menu, or via the command line using the standard syntax:
myobject.view_name(options) [args]
myobject.proc_name(options) [args]

See “User Object Views,” on page 1122 and “User Object Procs,” on page 1122 for a listing of
the built-in views and procs.

Data Members
The @hasmember(obname) function, available as a data member for all user objects,
returns a boolean value depending on whether an object called obname currently exists
inside the User Object.
User Object Programming Support—259

The @members data member returns a space delimited string containing a list of all objects
currently inside the user object.

See “User Object Data Members,” on page 1122.


260—Chapter 9.User Object Programming Support
Chapter 10. User-Defined Optimization

EViews offers a wide variety of built-in estimation methods that involve optimization,
including (but not limited to) those supported by the Equation, System, Sspace, and VAR
objects.

In addition, the EViews Logl object lets you maximize user-defined likelihood functions.
While useful in a wide range of settings, the Logl object is nevertheless restricted in the
types of functions that it can handle. In particular, the Logl requires that all computations be
specified using series expressions, and that the log-likelihood objective can be expressed as
a series containing log-likelihood contributions for each observation.

In contrast, the optimize (p. 525) command provides tools that allow you to find the opti-
mal parameters or control values of a user-defined function. Notably, optimize supports
quite general functions so that the computations and the user-defined objective need not be
series-based.

Defining the Objective and Controls


To use optimize, you must first construct an EViews subroutine with arguments to define
an output objective which depends on input controls.

Recall that a subroutine with arguments is simply a set of commands in a program that can
be called one or more times within the program (“Subroutine with Arguments” on
page 169). The arguments of the subroutine will correspond to the objective and to inputs
that are required to calculate the objective. Each time the subroutine is called, the objective
will be computed using the current values of the input controls.

The objective, which must be associated with an argument of the subroutine, may be a sca-
lar, or may consist of many values stored in an EViews object such as a vector, matrix, or
series.

The controls, which may be thought of as input parameters, are passed into the subroutine
as an argument. As with the objective, the controls may be a scalar value, or a multi-valued
object such as a vector, matrix, or series.

Note that when series objects are employed as either the objective or control, only the corre-
sponding elements in the current workfile sample will be used.

optimize will determine the values of the controls that optimize the objective. If the objec-
tive is many-valued, EViews will optimize the sum or sum-of-squares of the values, with
respect to the control elements.
262—Chapter 10.Defining the Objective and Controls

Since the objective is defined using an EViews subroutine, you may optimize almost any-
thing that may be computed using EViews commands. Notable, you may use optimize to
optimize general functions as well as likelihoods involving matrix computations (neither of
which may be optimized using the Logl object).

Consider, for example, the simple quadratic function defined as an EViews subroutine:
subroutine f(scalar !y, scalar !x)
!y = 5*!x^2 - 3*!x - 2
endsub

This subroutine has one output and one input, the program variable scalars !X and !Y,
respectively. For a given control value for !X, the subroutine computes the value of the sca-
lar objective !Y.

In its simplest form, a subroutine designed to work with optimize requires only two argu-
ments—an objective and control parameters. However you may include additional argu-
ments, some of which may be used by optimize, while others are ignored. For example, the
subroutine,
subroutine SqDev(series out, scalar in, series y)
out = (y - in)^2
endsub

computes the squared deviations of the argument series Y from the control scalar, and
places the element results in the output objective series OUT. The subroutine argument for
the series Y will not be used by optimize, but allows optimization to be performed on arbi-
trary series without re-coding the subroutine.

By default, optimize will assume that the first subroutine argument corresponds to the
objective and the second argument corresponds to the controls. As we will see, the default
associations may be changed through the use of options in the optimize command (“The
Optimize Command” on page 263).

Typically, multiple control values are passed into the subroutine in the form of a vector or
matrix, as in
subroutine local loglike(series logl, vector beta, series dep,
group regs)
!pi = @acos(-1)
series r = dep - beta(1) - beta(2)*regs(1) - beta(3)*regs(2) -
beta(4)*regs(3)
logl = @log((1/beta(5)*@dnorm(r/beta(5))
endsub

where the control vector BETA and the auxiliary arguments for the dependent variable series
DEP and the regressors group REGS are used as inputs for the computation of the normal
The Optimize Command—263

log-likelihood contributions in the objective series LOGL. Note that the first four elements of
the vector BETA correspond to the mean regression coefficients, and the last element is the
parameter for the standard deviation of the error distribution.

Lastly, when designing your subroutine, you should always define the objective to return
NA values for bad control values, since returning an arbitrary value may make numeric
derivatives unreliable at points close to the invalid region.

The Optimize Command


The syntax for the optimize command is:
optimize(options) subroutine_name(arguments)
where subroutine_name is the name of the defined subroutine in your program (or included
programs). The full set of options is provided in optimize (p. 525),

By default, EViews will assume that the first argument of the subroutine is the objective of
the optimization, and that the second argument contains the controls. The default is to max-
imize the objective or sum of the objective values (with the sum taken over the current
workfile sample, if a series).

Specifying the Method and Objective


You may control the type of optimization and which subroutine argument corresponds to
the objective by providing one of the following options to the optimize command:
• max [=integer]
• min [=integer]
• ls [=integer]
• ml [=integer]

The four options correspond to different optimization types: maximization (“max”), minimi-
zation (“min”), least squares (“ls”) and maximum likelihood (“ml”). If the objective is sca-
lar valued only “max” and “min” are allowed.

As the names suggest, “min” and “max” correspond to minimizing and maximizing the
objective. If the objective is multi-valued, optimize will minimize or maximize the sum of
the elements of the objective.

“ls” and “ml” are special forms of minimization and maximization that may be specified
only if the multi-valued objective argument has a value for each observation. “ls” tells
optimize that you wish to perform least squares estimation so the optimizer should mini-
mize the sum-of-squares of the elements of the objective. “ml” informs optimize you wish
264—Chapter 10.The Optimize Command

to perform maximum likelihood estimation by maximizing the sum of the elements in the
objective.

“ls” and “ml” differ from “min” and “max” in supporting an additional option for approxi-
mating the Hessian matrix (see “Calculating the Hessian” on page 265) that is used in the
estimation algorithm. Indeed the only difference between the “max” and “ml” for a multi-
valued objective is that “ml” supports the use of this option (“hess=opg”).

By default, the first argument of the subroutine is taken as the objective. However you may
specify an alternate objective argument by providing an integer value identifier with one of
the options above. For example, to identify the second argument of the subroutine as the
objective in a minimization problem, you would use the option “min=2”.

Identifying the Control


By default, the second argument in the subroutine contains the controls for the optimiza-
tion. You may modify this by including the “coef=integer” option in the optimize com-
mand, where integer is the argument identifier. For example, to identify the first argument of
the subroutine as the control, you would use the option “coef=1”.

Starting Values
The values of the objects containing the control parameters at the onset of optimization are
used as starting values for the optimization process. You should note that if any of the con-
trol parameters contain missing values at the onset of optimization, or if the objective func-
tion, or any analytic gradients cannot be evaluated at the initial parameter values, EViews
will error and the optimization process will terminate.

Specifying Gradients
If included in the optimize command, the “grad=” option specifies which subroutine
argument contains the analytic gradients for each of the coefficients. If you specify the
“grad=” option, the subroutine should fill out the elements of the gradient argument with
values of the analytical gradients at the current coefficient values.
• If the objective argument is a scalar, the gradient argument should be a vector of
length equal to the number of elements in the coefficient argument.
• If the objective argument is a series, the gradient argument should be a group object
containing one series per element of the coefficient argument. The series observations
should contain the corresponding derivatives for each observation in the current
workfile sample.
• For a vector objective, the gradient argument should be a matrix with number of rows
equal to the length of the objective vector, and columns equal to the number of ele-
ments in the coefficient argument.
The Optimize Command—265

• “grad=” may not be specified if the objective is a matrix.

If “grad=” is not specified, optimize will use numeric gradients. In general, we have found
that using numerical gradients performs as well as analytic gradients. Since programming
the calculation of the analytic gradients into the subroutine can be complicated, omitting the
“grad=” option should usually be one’s initial approach.

Calculating the Hessian


The “hess=” option tells EViews which Hessian approximation should be used in the esti-
mation algorithm. You may employ numeric Hessian (“hess=numeric”), Broyden-Fletcher-
Goldfarb-Shanno (“hess=bfgs”), or outer-product of the gradients (“hess=opg”) approxi-
mations to the Hessian (see “Hessian Approximation” on page 273).

You may not specify an analytic Hessian, though all three approximations use information
from the gradients, so that there will be slight differences in the Hessian calculation depend-
ing on whether you use numeric versus analytical gradients.

The “finalh=” option allows you to save the Hessian matrix of the optimization problem at
the final coefficient values as a matrix in the workfile. For least squares and maximum like-
lihood problems, the Hessian is commonly used in the calculation of coefficient covariances.

For OPG and numeric Hessian approximations, the final Hessian will be the same as the
Hessian approximation used during optimization. For BFGS, the final Hessian will be based
on the numeric Hessian, since the BFGS approximation need not converge to the true Hes-
sian.

Numeric Derivatives
You can control the method of computing numeric derivatives for gradient or Hessian calcu-
lations using the “deriv=” option.

At the default setting of “deriv=auto”, EViews will change the number of numeric deriva-
tive evaluation points as the optimization routine progresses, switching to a larger number
of points as it approaches the optimum.

When you include the “deriv=high” option, EViews will always evaluate the objective func-
tion at a larger number of points.

Iteration and Convergence


The “m=” and “c=” options set the maximum number of iterations, and the convergence
criterion respectively. Note that for optimization, the number of iterations is the number of
successful steps that take place, and that each iteration may involve many function evalua-
tions, both to evaluate any required numeric derivatives and for backtracking in cases where
a trial step fails to improve the objective.
266—Chapter 10.The Optimize Command

Reaching the maximum number of iterations will cause an error to occur (unless the “noerr”
option is set).

Advanced Optimization Options


There are several advanced options which control different aspects of the optimization pro-
cedure. In general, you should not need to worry about these settings, but they may prove
useful in cases where you are experiencing estimation difficulties.

Trust Region
You may use the “trust=” option to set the initial trust region size as a proportion of the ini-
tial control values. The default trust region size is 0.25.

Smaller values of this parameter may be used to provide a more cautious start to the optimi-
zation in cases where larger steps immediately lead into an undesirable region of the objec-
tive.

Larger values may be used to reduce the iteration count in cases where the objective is well
behaved but the initial values may be far from the optimum values.

See “Technical Details,” on page 272 for discussion.

Step Method
optimize offers several methods for determining the constrained step size which you may
specify using the “step=” option. In additional to the default Marquardt method
(“step=marquardt”), you may specify dogleg steps (“step=dogleg”) or a line-search deter-
mined step (“step=linesearch”).

Note that in most cases the choice of step method is less important than the selection of
Hessian approximation. See “Step Method,” on page 275 for additional detail.

Scale
By default, the optimization procedure automatically adjusts the scale of the objective and
control variables using the square root of the maximum observed value of the second deriv-
ative (curvature) of each control parameter. Scaling may be switched off using the
“scale=none” option. See “Scaling,” on page 276 for discussion.

Objective Accuracy
The “feps=” option may be used to specify the expected relative accuracy of the objective
function. The default value is 2.2e-16.

The value indicates what fraction of the observed objective value should be considered to be
random noise. You may wish to increase the “feps=” value if the calculation of your objec-
tive may be relatively inaccurate.
Examples—267

Status Functions
To support the optimize command, EViews provides three functions that return informa-
tion about the optimization process:
• @optstatus provides a status code for the optimizer, both during and post-optimiza-
tion.
• @optiter returns the current number of iterations performed. If called post-optimiza-
tion, it will return the number of iterations required for convergence.
• @optmessage returns a one line text message based on status and iteration informa-
tion that summarizes the current state of an optimization.

All three of these functions may be used during optimization by including them inside the
optimization subroutine, or post-optimization by calling them after the optimize com-
mand.

Error Handling
The “noerr” option may be used as an option to suppress any error messages created when
the optimization fails. By default, the optimization procedure will generate an error when-
ever the results of the optimization appear to be unreliable, such as if convergence was not
met, or the gradients are non-zero at the final solution.

If noerr is specified, these errors will be suppressed. In this case, your EViews program may
still test whether the optimization succeeded using the @optiter function. Note that the
noerr option is useful in cases where you are deliberately stopping optimization early using
the m= maximum iterations option, since otherwise this will generate an error.

Examples
We demonstrate the use of the optimize command with several examples. To begin, we
consider a regression problem using a workfile created with the following set of commands:
wfcreate u 100
rndseed 1
series e = nrnd
series x1 = 100*rnd
series x2 = 30*nrnd
series x3 = -4*rnd
group xs x1 x2 x3
series y = 3 + 2*x1 + 4*x2 + 5*x3 + e
equation eq1.ls y c x1 x2 x3

These commands create a workfile with 100 observations, and then generate some random
data for series X1, X2 and X3, and E (where E is drawn from the standard normal distribu-
tion). The series Y is created as 3+2*X1+4*X2+5*X3 + E.
268—Chapter 10.Examples

To establish a baseline set of results for comparison, we regress Y against a constant, X1, X2,
and X3 using the built-in least squares method of the EViews equation object. The results
view for the resulting equation EQ1 contains the regression output:

Next we use the optimize command with the least squares method to estimate the coeffi-
cients in the regression problem. Running a program with the following commands pro-
duces the same results as the built-in regression estimator:
subroutine leastsquares(series r, vector beta, series dep, group
regs)
r = dep - beta(1) - beta(2)*regs(1) - beta(3)*regs(2) -
beta(4)*regs(3)
endsub

series LSresid
vector(4) LSCoefs
lscoefs = 1
optimize(ls=1, finalh=lshess) leastsquares(LSresid, lscoefs, y, xs)
scalar sig = @sqrt(@sumsq(LSresid)/(@obs(LSresid)-@rows(LSCoefs)))
vector LSSE = @sqrt(@getmaindiagonal(2*sig^2*@inverse(lshess)))

We begin by defining the LEASTSQUARES subroutine which computes the regression resid-
ual series R, using the parameters given by the vector BETA, the dependent variable given
by the series DEP, and the regressors provided by the group REGS. All of these objects are
arguments of the subroutine which are passed in when the subroutine is called.

Next, we declare the LSRESID series and a vector of coefficients, LSCOEFS, which we arbi-
trarily initialize at a value of 1 as starting values.
Examples—269

The optimize command is called with the “ls” option to indicate that we wish to perform a
least squares optimization. The “finalh” option is included so that we save the estimated
Hessian matrix in the workfile for use in computing standard errors of the estimates. opti-
mize will find the values of LSCOEFS that minimize the sum of squared values of LSRESID
as computed using the LEASTSQUARES subroutine.

Once optimization is complete, LSCOEFS contains the point estimates of the coefficients. For
least squares regression, the standard error of the regression s is calculated as the square
root of the sum of squares of the residuals, divided by T – k . We store s in the scalar SIG.
Standard errors may be calculated from the Hessian as the square root of the diagonal of
2 –1
2s H . We store these values in the vector LSSE.
The coefficients in LSCOEFS, standard error of the regression s in SIG, and coefficient stan-
dard errors in LSSE, all match the results in EQ1.

Alternately, we may use optimize to estimate the maximum likelihood estimates of the
regression model coefficients. Under standard assumptions, an observation-based contribu-
tion to the log-likelihood for a regression with normal error terms is of the form:

 1  –et2   1 e
-    log  --- f  ----t  
L t  log  -------------- exp  --------- (10.1)
 j 2p  2j   2  j  j 

The following code obtains the maximum likelihood estimates for this model:
subroutine loglike(series logl, vector beta, series dep, group regs)
series r = dep - beta(1) - beta(2)*regs(1) - beta(3)*regs(2) -
beta(4)*regs(3)
logl = @log((1/beta(5))*@dnorm(r/beta(5)))
endsub

series LL
vector(5) MLCoefs
MLCoefs = 1
270—Chapter 10.Examples

MLCoefs(5) = 100
optimize(ml=1, finalh=mlhess, hess=numeric) loglike(LL, MLCoefs, y,
xs)
vector MLSE = @sqrt(@getmaindiagonal(-@inverse(mlhess)))
scalar ubsig = mlcoefs(5)*@sqrt(@obs(LL)/(@obs(LL) - @rows(MLCoefs)
+ 1))
%status = @optmessage
statusline {%status}

The subroutine LOGLIKE computes the regression residuals using the coefficients in the vec-
tor BETA, the dependent variable series given by DEP, and the regressors in the group REGS.
Given R, the subroutine evaluates the individual log-likelihood contributions and puts the
results in the argument series LOGL.

The next lines declare the series LL to hold the likelihood contributions and the coefficient
vector BETA to hold the controls. Note that the coefficient vector, BETA, has five elements
instead of the four used in least-squares optimization, since we are simultaneously estimat-
ing the four regression coefficients and the error standard deviation j . We arbitrarily initial-
ize the regression coefficients to 1 and the distribution standard deviation to 100.

We set the maximizer to perform a maximum likelihood based estimation using the “ml=”
option and to store the OPG Hessian in the workfile in the sym objected MLHESS. The coef-
ficient standard errors for the maximum likelihood estimates may be calculated as the
square root of the main diagonal of the negative of the inverse of MLHESS. We store the esti-
mated standard errors in the vector MLSE.

Although the regression coefficient estimates match those in the baseline, the ML estimate
of j in the fifth element of BETA differs. You may obtain the corresponding unbiased esti-
mate of sigma by multiplying the ML estimate by multiplying BETA(5) by T   T – k  ,
which we calculate and store in the scalar UBSIG.
Examples—271

Note also that we use @optmessage to obtain the status of estimation, whether convergence
was achieved and if so, how many iterations were required. The status is reported on the
statusline after the optimize estimation is completed.

The next example we provide shows the use of the “grads=” option. This example re-calcu-
lates the least-squares example above, but provides analytic gradients inside the subroutine.
Note that for a linear least squares problem, the derivatives of the objective with respect to
the coefficients are the regressors themselves (and a series of ones for the constant):
subroutine leastsquareswithgrads(series r, vector beta, group grads,
series dep, group regs)
r = dep - beta(1) - beta(2)*regs(1) - beta(3)*regs(2) -
beta(4)*regs(3)
grads(1) = 1
grads(2) = regs(1)
grads(3) = regs(2)
grads(4) = regs(3)
endsub

series LSresid
vector(4) LSCoefs
lscoefs = 1
series grads1
series grads2
series grads3
series grads4
group grads grads1 grads2 grads3 grads4
optimize(ls=1, grads=3) leastsquareswithgrads(LSresid, lscoefs,
grads, y, xs)

Note that the series for the gradients, and the group containing those series, were declared
prior to calling the optimize command, and that the subroutine fills in the values of the
series inside the gradient group.

Up to this point, our examples have involved the evaluation of series expressions. The opti-
mizer does, however, work with other EViews commands. We could, for example, compute
the least squares estimates using the optimizer to “solve” the normal equation
 XX b  XY for b . While the optimizer is not a solver, we can trick it into solving that
equation by creating a vector of residuals equal to  XX b – XY , and asking the opti-
mizer to find the values of b that minimize the square of those residuals:
subroutine local matrixsolve(vector rvec, vector beta, series dep,
group regs)
stom(regs, xmat)
xmat = @hcat(@ones(100), xmat)
stom(dep, yvec)
rvec = @transpose(xmat)*xmat*beta - @transpose(xmat)*yvec
272—Chapter 10.Technical Details

rvec = @epow(rvec,2)
endsub
vector(4) MSCoefs
MSCoefs = 1
vector(4) rvec
optimize(min=1) matrixsolve(rvec, mscoefs, y, xs)

Since we will be using matrix manipulation for the objective function, the first few lines of
the subroutine convert the input dependent variable series and regressor group into matri-
ces. Note that the regressor group does not contain a constant term upon input, so we
append a column of ones to the regression matrix XMAT, using the @hcat command.

Lastly, we use the optimize command to find the minimum of a simply function of a single
variable. We define a subroutine containing the quadratic form, and use the optimize com-
mand to find the value that minimizes the function:
subroutine f(scalar !y, scalar !x)
!y = 5*!x^2 - 3*!x - 2
endsub
create u 1
scalar in = 0
scalar out = 0
optimize(min) f(out, in)

This example first creates an empty workfile and declares two scalar objects, IN and OUT,
for use by the optimizer. IN will be used as the parameter for optimization, and is given an
arbitrary starting value of 0. The subroutine F calculates the simple quadratic formula:
2
Y  5X – 3X – 2 (10.2)

After running this program the value of IN will be 0.3, and the final value of OUT (evaluated
at the optimal IN value) is -2.45. As a check we can manually calculate the minimal value of
the function by taking derivatives with respect to X, setting equal to zero, and solving for X:
dY
-------  10X – 3
dX (10.3)
X  0.3

Technical Details
The optimization procedure uses a Newton (or quasi-Newton) based approach to optimiza-
tion. In this approach, the first and second derivatives of the objective are used to form a
local quadratic approximation to the objective function around the current value of the con-
trol parameters. The procedure then calculates the change in the control values that would
maximize (or minimize) the objective if the objective function were to exactly follow the
local approximation.
Technical Details—273

Mathematically, if the local approximation of the objective f around the control values
x  x is:
1
min f  p   f  x   g  x p  --- pH  x p (10.4)
2
where f is the objective function, g is the gradient, and H is the Hessian, then the first-
order conditions for a maximum give the following expression for the Newton step:
–1
p  – H  x  g  x  (10.5)

Note that this local approximation may become quite inaccurate as we move away from the
current parameter values. At the full Newton step, the objective may improve by much less
than the approximation suggests, or may even worsen. To deal with this possibility, the opti-
mization procedure uses a trust region approach (More and Sorensen, 1983). In the trust
region approach, the local quadratic approximation is only maximized within a limited
neighborhood of the current control values, so that the change in control values at each step
is not allowed to exceed a current maximum step size. We then evaluate the objective at the
new proposed parameter values. If the local approximation appears to be accurate, the max-
imum allowed step size is increased. If the local approximation appears to be inaccurate, the
maximum allowed step size is decreased. A step is only accepted when it results in a suffi-
ciently large reduction in the objective relative to the reduction that was predicted by the
local approximation.

Mathematically the constrained step can be written as:


min f  p  s.t. p  d (10.6)

where d is the trust region maximum step size. In the case where the maximum step con-
straint is binding, typically the step has a solution
–1
p  –  H  x   lI  g  x  (10.7)

where l is chosen so that | p  d.


Note that the Newton approach will work best when the objective can be fitted reasonably
well by a local quadratic approximation. This will not be the case if the function is discon-
tinuous or has discontinuous first or second derivatives. In these cases, the procedure may
be slow to find an optimum, and the final parameter values may end up adjacent to a dis-
continuity so that the results will need to be interpreted with caution.

Hessian Approximation
In the discussion above we assumed that the Hessian matrix of second derivatives of the
objective with respect to the control parameters are readily available. In practice these deriv-
atives will need to be approximated. The optimize procedure provides three different
methods: numeric Hessian, Broyden-Fletcher-Goldfarb-Shanno (BFGS), outer-product of the
gradients (OPG).
274—Chapter 10.Technical Details

Numeric Hessian
The numeric Hessian approach approximates the Hessian using numeric derivatives. If ana-
lytic gradients are provided, the Hessian is based on taking numeric first derivatives of the
analytic gradients. If analytic gradients are not provided, the Hessian is based on numeric
second derivatives of the objective function.

You may specify the use of numeric Hessians by including the option “hess=numeric”
option in the optimize command.

Note that calculating numeric second derivatives may require many evaluations of the
objective function. In the case of numeric second derivatives, each Hessian approximation
will require additional evaluations proportional to the square of the number of control
parameters in the problem. For a large number of control parameters, this method may be
quite slow.

Broyden-Fletcher-Goldfarb-Shanno (BFGS)
The Broyden-Fletcher-Goldfarb-Shanno (BFGS) method approximates the Hessian using an
updating scheme where the previous iteration's approximation to the Hessian is adjusted
after each step based on the observed change in the gradients.

The BFGS update makes as small a change as possible to the existing Hessian approximation
so that it is compatible with the observed change in gradients, while ensuring that the
approximation to the Hessian remains positive definite. (See Chapter 9 of Dennis and Schna-
bel (1983) for a detailed discussion.)

To specify the BFGS method, use the optimize command with the “hess=bfgs” option.

BFGS requires fewer objective function evaluations per step than computing a numeric Hes-
sian, but may take more iterations to converge. Note that the BFGS approximation need not
converge to the true Hessian at the optimized control parameter values, so it cannot be used
for calculating the coefficient covariances in statistical problems. Note also that the itera-
tions are started from a diagonal approximation to the Hessian.

Outer-product of Gradients (OPG)


For certain statistical problems, the Hessian can be approximated by a multiple of the sum of
the outer products of the gradients (OPG) of individual contributions to the total objective
with respect to the coefficients. In the case of least squares problems, this method is com-
monly referred to as the Gauss-Newton method. In maximum likelihood settings, this
method is often referred to as the BHHH (Berndt, Hall, Hall, and Hausman, 1974) method.

In both settings, the approximations are based on the statistical idea that the expected value
of the Hessian at the optimized parameter values is equal to a multiple of the expected value
of the sum of the outer product of gradients and that the two will converge as the sample
Technical Details—275

size becomes large. The asymptotic equivalence implies that these OPG approximations will
be closer to the true Hessian when working with medium to large sample sizes and when
coefficients are close to the true coefficient values.

You may select the OPG approximation using the “hess=opg” option.

Note that the OPG method may only be used when the objective is a set of least squares
residuals (specified using the “ls” option) or a set of maximum likelihood contributions
(specified using the “ml” option), since there is no reason to believe the approximation is
valid for an arbitrary maximization or minimization objective.

OPG uses the same number of objective evaluations per step as BFGS, which is less than the
number required for evaluating the numeric Hessian.

Step Method
Different step methods are supported by optimize, with each following a trust region
approach, where the full Newton step is taken whenever the step is less than the current
maximum step size, and a constrained step is taken when the full Newton step exceeds the
current maximum step size. The methods differ in how the constrained step is taken. Note
that in most cases, the choice of step method is less important than the selection of Hessian
approximation.

Marquardt
The default Marquardt option closely follows the method outlined above where the con-
strained step is calculated by an iterative procedure that searches for a diagonal adjustment
to the Hessian that makes the step size equal to the maximum allowed step size. The Mar-
quardt step has the highest computational cost, although since for most statistical estima-
tion most computation time is spent evaluating the objective rather than calculating an
optimal step, this is unlikely to matter unless the number of controls is fairly large and the
objective can be evaluated cheaply.

Dogleg
The dogleg method is a cheaper approximation to the trust region problem where the con-
strained step is calculated by combining a Newton step with a Cauchy step (a step in the
direction of the scaled gradients that minimizes the local quadratic approximation to the
objective). For both the Marquardt and dogleg steps, the direction of the step shifts away
from the direction of the Newton step towards the direction of steepest descent as the trust
region contracts, but the dogleg step uses a simple linear combination of the two steps to
achieve this. When the dogleg step is used with a BFGS Hessian (the hess=bfgs option)
approximation, the calculations required per iteration are proportional to the square rather
than the cube of the number of parameters. This makes the dogleg step attractive if the
number of control variables is very large and the objective can be evaluated cheaply.
276—Chapter 10.Technical Details

Line-search
The line-search method is the simplest approach in which the constrained step is formed by
proportionally scaling down the Newton step until it satisfies the maximum step size con-
straint. With this method, only the length of the step is changed as the trust region con-
tracts, but not its direction. The line-search method is the cheapest method in terms of
calculational cost but may be less robust, particularly when used with poor initial values.

Note that for both the dogleg and line-search algorithms, an adjustment will be made to the
diagonal of the Hessian to ensure positive definiteness before calculating the Newton step.
There is also special handling for non-positive definite matrices in the Marquardt step fol-
lowing the method outlined in More and Sorensen (1983).

Scaling
The Newton step is theoretically invariant to both the scale of the objective and the scale of
the control variables since any changes to the gradients and the Hessian cancel each other
out in the expression for the Newton step. In practice, numerical issues may cause the
equivalence to be inexact. Additionally, the constrained trust region steps do not have the
invariance property unless scaling is applied to the control variables when calculating a con-
strained step.

By default, the optimization procedure scales automatically using the square root of the
maximum observed value of the second derivative (curvature) of each control parameter.
This makes the procedure theoretically invariant to the scaling of the variables.

In most cases you should leave the default scaling turned on, but in cases where the Hessian
approximation may be unreliable, scaling may be switched off using the “scale=none”
option. When scaling is switched off, you may wish to define your objective so that equal
size changes to each control variable will have a similar order of magnitude of impact on the
objective.

Optimization Termination
The optimization process will terminate immediately if the initial control parameters contain
missing values, the objective function, or if provided, the analytical gradients cannot be
evaluated at the starting parameter values.

Once the optimization procedure begins, it will proceed even if numerical errors (such as
taking the log of a negative number) prevent the objective function from being evaluated at
a trial step. An objective with missing values will be taken as indicating that the control val-
ues are invalid, and the optimization will step back from the problematic values.

Note that you should always define the objective to return NA values for bad control values
since returning an arbitrary value may make numeric derivatives unreliable at points close
to the invalid region.
Technical Details—277

The optimization procedure will terminate when:


• An unconstrained Newton step improved the objective and the length of the step was
less than the specified convergence tolerance.
• A constrained step failed to improve the objective and the maximum allowed step size
for the next iteration was decreased to become less than the specified convergence tol-
erance.
• The maximum number of iterations (successful steps) was reached without one of the
above criteria being met.

When the procedure terminates for a condition other than the maximum iterations being
reached, the procedure checks the gradients and curvature of the objective to see whether
the first and second order conditions for an optimum appear to be satisfied. If the conditions
are not met, the optimization will be considered to have failed. There are a variety of rea-
sons that failure may occur:
• The objective may have no optimum value, but just gradually flatten out as a control
variable becomes very large or small.
• The objective may not be defined for some values of the control parameters but may
improve as we approach these values. This will cause the optimization to stall with
control variables very close to the invalid region, but with non-zero gradients at the
final control values.
• There may be values for some controls which make other controls included in the
optimization have little or no impact on the objective, so that both the gradients and
the elements of the Hessian corresponding to the variables gradually become zero as
the optimization progresses.
• The control variables may 'collapse' so that two or more controls are serving the same
role in the objective and their individual effect cannot be separated. This will result in
a Hessian that is numerically singular since changes in one control can be exactly off-
set by changes in one or more of the other controls without changing the objective.
(For statistical problems, this implies that the coefficients are unidentified).

In all these cases, a useful approach is to carefully consider starting values so that the initial
values for the controls are as close as possible to what you believe the optimum values
might be. You should also avoid starting values that are close to any regions in which the
objective function cannot be evaluated. If the optimization continues to report problems
from a wide range of starting values, this may indicate that your optimization problem is not
well defined.

Successful convergence does not guarantee that the optimization procedure has found the
global optimum of the function. The optimization procedure only tests whether the final
point appears to satisfy the conditions necessary for a local optimum. In cases where more
278—Chapter 10.References

than one local optimum may exist, the optimization procedure may converge to different
final values depending on what starting values are used.

Note that when the optimization completes successfully (no error is reported) the last call to
the subroutine that calculates the objective will always be with the control parameters set to
the optimized values. (An additional final call to the subroutine will be made in situations
where this is not already the case). This guarantees that any intermediate results saved
inside the subroutine will also be left at their optimized results after the optimization is com-
plete.

References
Berndt, E., Hall, B., Hall, R., and Hausman, J. (1974). Estimation and Inference in Nonlinear Structural
Models, Annals of Economic and Social Measurement, Vol. 3, 653–665.
Dennis, J. E. and R. B. Schnabel (1983). “Secant Methods for Systems of Nonlinear Equations,” Numerical
Methods for Unconstrained Optimization and Nonlinear Equations. Prentice-Hall, London.
More and Sorensen (1983). Computing a Trust Region Step, SIAM Journal of Scientific Statistical Comput-
ing, Vol. 4, 553–572.
Chapter 11. Matrix Language

EViews provides you with tools for working directly with data contained in matrices and
vectors. You can use the EViews matrix language to perform calculations that are not avail-
able using the built-in views and procedures.

The following objects may be created and manipulated using the matrix command lan-
guage:
• matrix: two-dimensional array.
• vector: column vector.
• sym: symmetric matrix (stored in lower triangular form).
• scalar: scalar.
• rowvector: row vector.
• coef: column vector of coefficients to be used by equation, system, pool, logl, and
sspace objects.

We term these objects matrix objects (despite the fact that some of these objects are not
matrices).

Declaring Matrix Objects


You must declare a matrix object for it to exist in the workfile. A listing of the declaration
statements for the various matrix objects is provided in “Object Creation Commands” on
page 357.

Briefly, a matrix object declaration consists of the object keyword, along with size informa-
tion in parentheses and the name to be given to the object, followed (optionally) by an
assignment statement. If no assignment is provided, the object will be initialized to have all
zero values.

The various matrix objects require different sizing information. A matrix requires the num-
ber of rows and the number of columns. A sym requires that you specify a single number
representing both the number of rows and the number of columns. A vector, rowvector, or
coef declaration can include information about the number of elements. A scalar requires no
size information. If size information is not provided, EViews will assume that there is only
one element in the object.

For example:
matrix(3,10) xdata
sym(9) moments
280—Chapter 11.Assigning Matrix Values

vector(11) betas
rowvector(5) xob

creates a 3  10 matrix XDATA, a symmetric 9  9 matrix MOMENTS, an 11  1 column


vector BETAS, and a 1  5 rowvector XOB. All of these objects are initialized to zero.

To change the size of a matrix object, you may repeat the declaration statement. Further-
more, if you use an assignment statement with an existing matrix object, the target will be
resized as necessary. For example:
sym(10) bigz
matrix zdata
matrix(10,2) zdata
zdata = bigz

will first declare ZDATA to be a matrix with a single element, and then redeclare ZDATA to
be a 10  2 matrix. The assignment statement in the last line will resize ZDATA so that it
contains the contents of the 10  10 symmetric matrix BIGZ.

Assigning Matrix Values


There are three ways to assign values to the elements of a matrix: you may assign values to
specific matrix elements, you may fill the matrix using a list of values, or you may perform
matrix assignment.

Element assignment
The most basic method of assigning matrix values is to assign a value for a specific row and
column element of the matrix. Simply enter the matrix name, followed by the row and col-
umn indices, in parentheses, and then an assignment to a scalar value.

For example, suppose we declare the 2  2 matrix A:


matrix(2,2) a

The first command creates and initializes the 2  2 matrix A so that it contains all zeros.
Then after entering the two commands:
a(1,1) = 1
a(2,1) = 4

we have

A  1 0 . (11.1)
4 0

You can perform a large number of element assignments by placing them inside of program-
ming loops:
Assigning Matrix Values—281

vector(10) y
matrix (10,10) x
for !i = 1 to 10
y(!i) = !i
for !j = 1 to 10
x(!i,!j) = !i + !j
next
next

Note that the fill procedure provides an alternative to using loops for assignment (see, for
example, the matrix object version of the procedure, Matrix::fill).

Fill assignment
The second assignment method is to use the fill object procedure to assign a list of num-
bers to each element of the matrix in the specified order. By default, the procedure fills the
matrix column by column, but you may override this behavior to fill by rows.

You should enter the name of the matrix object, followed by a period, the fill keyword,
and then a comma delimited list of values. For example, the commands:
vector(3) v
v1.fill 0.1, 0.2, 0.3
matrix(2,4) x
matrix.fill 1, 2, 3, 4, 5, 6, 7, 8

create the matrix objects:

0.1
V  X  1 3 5 7
0.2 , (11.2)
2 4 6 8
0.3

If we replace the last line with


matrix.fill(b=r) 1,2,3,4,5,6,7,8

then X is given by:

X  1 2 3 4 . (11.3)
5 6 7 8

In some situations, you may wish to repeat the assignment over a list of values. You may use
the “l” option to fill the matrix by repeatedly looping through the listed numbers until the
matrix elements are exhausted. Thus,
matrix(3,3) y
282—Chapter 11.Assigning Matrix Values

y.fill(l) 1, 0, -1

creates the matrix:

1 1 1
Y  0 0 0 (11.4)
–1 –1 –1

See Matrix::fill for a complete description of the fill procedure for a matrix. Equivalent
procedures are available for the remaining matrix objects.

Matrix assignment
You can copy data from one matrix object into another using assignment statements. To per-
form an assignment, you should enter the name of the target matrix followed by the equal
sign “=”, and then a matrix object expression. The expression on the right-hand side should
either be a numerical constant, a matrix object, or an expression that returns a matrix
object.

There are rules for how EViews performs the assignment which vary depending upon the
types of objects involved in the assignment.

Initialize to Scalar Value


If there is a scalar on the right-hand side of the assignment, every element of the matrix
object is assigned the value of the scalar.

Examples:
matrix(5,8) first
scalar second
vec(10) third
first = 5
second = c(2)
third = first(3,5)

Since declaration statements allow for initialization, you can combine the declaration and
assignment statements. Examples:
matrix(5,8) first = 5
scalar second = c(2)
vec(10) third = first(3,5)

Initialize Using Compatible Matrix


If the source object on the right is a matrix or vector, and the target or destination object on
the left is of the same type, the target will be resized to have the same dimension as the
source, and every source element will be copied. For example:
Assigning Matrix Values—283

matrix(10,2) zdata = 5
matrix ydata = zdata
matrix(10,10) xdata = ydata

declares that ZDATA is a 10  2 matrix filled with 5’s. In the second line, YDATA is auto-
matically resized to be a 10  2 matrix and is filled with the contents of ZDATA.

The third line declares and initializes XDATA. Note that even though the declaration of
XDATA calls for a 10  10 matrix, XDATA is a 10  2 matrix of 5’s. This behavior occurs
because the declaration statement above is equivalent to issuing the two commands:
matrix(10,10) xdata
xdata = ydata

which will first declare the 10  10 matrix XDATA, and then automatically resize it to
10  2 when you fill it with the values for YDATA (see also “Copying Data From Matrix
Objects” on page 285).

The matrix object on the right hand side of the declaration statement may also be the output
from a matrix function or expression. For example,
sym eye4 = @identity(4)

declares the symmetric matrix EYE4 which is equal to the 4  4 identity matrix, while
vector b = @inverse(xx)*xy

inverts the matrix XX, multiplies it by XY, and assigns the value to the new vector B.

The next section discusses assignment statements in the more general case, where you are
converting between object types. In some cases, the conversion is automatic; in other cases,
EViews provides you with additional tools to perform the conversion.

Initialize Using Creation Functions


One common operation, creating and filling a vector in one-step may be accomplished using
some specialized functions for creating specific types of vectors:
• @fill(n1, n2, n3, ...) – returns a numeric vector with the specified values.
• @range(n1, n2) – returns a numeric vector with the sequential integer values from n1
to n2.
• @seq(s, d, n) – returns a numeric vector with the arithmetic sequence of n elements
beginning with s and incrementing by d.
• @seqm(s, d, n) – returns a numeric vector with the multiplicative sequence of n ele-
ments beginning with s and incrementing by by the factor d.
• @grid(n1, n2, n3) – returns a numeric vector containing a grid of n3 values from n1
to n2.
284—Chapter 11.Assigning Matrix Values

• @unit(n1, n2, n3) – returns a numeric vector containing a grid of n3 values from n1
to n2.
• @ones(n1) – returns an n1 element vector of ones.
• @zeros((n1) – returns an n1 element vector of zeros.
• @unitvector(n1, n2) – returns an n1 element vector with a 1 in the n2-th element,
and 0 elsewhere.
• @filledvector(n1, n2) – returns an n1 element vector filled with n2.
• @filledrowvector(n1, n2) – returns an n1 element row vector filled with n2.
• @sfill("str1", "str2", "str3", ...) – returns a svector using the specified double-quote
enclosed strings.
• @wsplit("str1") – returns a svector by splitting the string into words.

Note that the all but the last two functions creates a vector object, while those two create an
svector (string vector) object.

These use of these functions are straightforward. While @fill and @seq will work with
arbitrary numeric values, one important application is in generating vectors of integer val-
ues.
vector x1 = @fill(1, 2, 4, 5, 7)

creates the vector with elements {1, 2, 4, 5, 7}, while


vector x2 = @range(1, 5)

creates the vector with elements {1, 2, 3, 4, 5}, while


vector x3 = @seq(1, 2, 4)

creates the vector with elements {1, 3, 5, 7}, while


vector x4 = @grid(1, 2, 6)

creates the vector with elements {1.0, 1.2, 1.4, 1.6, 1.8, 2.0}, and
svector sx1 = @sfill("apple", "pear", "orange")

creates the svector with the values {“apple”, “pear”, “orange”}.

Since these functions both create and initialize the vector, they are often used to provide
inputs to other functions:
scalar pythagoras = @sum(@range(1, 6))

Similarly, other commonly employed functions create and fill a matrix:


• @ones(n1, n2) – return an n1 by n2 matrix of ones.
• @zeros(n1, n2) – return an n1 by n2 matrix of zeros.
Copying Data Between Objects—285

• @identity(n1) – return an n1 by n1 symmetric identity matrix.


• @filledmatrix(n1, n2, n3) – return an n1 by n2 matrix filled with n3.
• @filledsym(n1, n2) – return an n1 by n1 symmetric matrix filled with n2.

While a matrix of ones may be created using either


matrix(10, 3) ones1 = 1
matrix ones2 = @ones(10, 3)

the latter is most useful for providing the matrix as an input to a second function
matrix k = @kronecker(@identity(10), @ones(10, 3))

Similarly, while you may create a vector with the value Pi using
vector(10) pimat = @pi

the filled vector function is useful for creating input for a function that requires a vector
matrix g = @hcat(@ones, @filledvector(10, @pi))

without explicitly declaring PIMAT.

Copying Data Between Objects


In addition to the basic assignment statements described in the previous section, EViews
provides you with a large set of tools for copying data to and from matrix objects.

At times, you may wish to move data between different types of matrix objects. For example,
you may wish to take the data from a vector and put it in a matrix. EViews has a number of
built-in rules which make these conversions automatically.

At other times, you may wish to move data between a matrix object and an EViews series or
group object. There are a separate set of tools which allow you to convert data across a vari-
ety of object types.

Copying Data From Matrix Objects


Data may be moved between different types of matrix objects using assignment statements.
If possible, EViews will resize the target object so that it contains the same information as
the object on the right side of the equation.

The basic rules governing expressions of the form “Y=X” may be summarized as follows:
• The object type of the target Y cannot change.
• The target object Y will, if possible, be resized to match the object X; otherwise,
EViews will issue an error. Thus, assigning a vector to a matrix will resize the matrix,
but assigning a matrix to a vector will generate an error if the matrix has more than
one column.
286—Chapter 11.Copying Data Between Objects

• The data in X will be copied to Y.

Specific exceptions to the rules given above are:


• If X is a scalar, Y will keep its original size and will be filled with the value of X.
• If X and Y are both vector or rowvector objects, Y will be changed to the same type as
X.

Here are some simple examples illustrating the rules for matrix assignment:
vector(3) x
x(1) = 1
x(2) = 2
x(3) = 3
vector y = x
matrix z = x

Y is now a 3 element vector because it has the same dimension and values as X. EViews
automatically resizes the Z Matrix to conform to the dimensions of X so that Z is now a
3  1 matrix containing the contents of X: Z(1,1)=1, Z(2,1)=2, Z(3,1)=3.
Here are some further examples where automatic resizing is allowed:
vector(7) y = 2
scalar value = 4
matrix(10,10) w = value
w = y
matrix(2,3) x = 1
rowvector(10) t = 100
x = t

W is declared as a 10  10 matrix of 4’s, but it is then reset to be a 7  1 matrix of 2’s. X is


a 1  10 matrix of 100’s.

Lastly, consider the commands:


vector(7) y = 2
rowvector(12) z = 3
coef(20) beta
y = z
z = beta

Y will be a rowvector of length 3, containing the original contents of Z, and Z will be a col-
umn vector of length 20 containing the contents of BETA.
Copying Data Between Objects—287

There are some cases where EViews will be unable to perform the specified assignment
because the resize operation is ill defined. For example, suppose that X is a 2  2 matrix.
Then the assignment statement:
vector(7) y = x

will result in an error. EViews cannot change Y from a vector to a matrix and there is no way
to assign directly the 4 elements of the matrix X to the vector Y. Other examples of invalid
assignment statements involve assigning matrix objects to scalars or sym objects to vector
objects.

It may be possible, however, to use the @vec (p. 1183), @vech (p. 1184), @unvec (p. 1170),
and @unvech (p. 1171) functions to reshape matrices and vectors into forms that permit
assignment.

Extracting Part of a Matrix Objects


The best way to extract data from a matrix object is to use matrix object member functions.

Basic Submatrix Extraction


The relevant functions for all matrix objects are:

• obj.@col(arg) – returns matrix object containing column(s) of obj associated with


arg

• obj.@row(arg) – returns matrix object containing row(s) of obj associated with arg
• obj.@sub(arg1, arg2) – returns matrix object containing row(s) and col(s) of obj
associated with arg1 and arg2, respectively
• obj.@dropcol(arg) – returns matrix object containing column(s) of obj not associated
with arg
• obj.@droprow(arg) – returns matrix object containing row(s) of obj not associated
with arg
• obj.@dropboth(arg1, arg2) – returns matrix object containing row(s) and col(s) of
obj not associated with arg1 and arg2, respectively

For symmetric matrices, we also have the functions

• obj.@sub(arg) – returns sym object containing row(s) and col(s) of obj associated
with arg, respectively
• obj.@dropboth(arg) – returns sym object containing row(s) and col(s) of obj not
associated with arg, respectively

where
288—Chapter 11.Copying Data Between Objects

• obj is the name of a matrix object in the workfile


• arg, arg1, arg2 are integers, scalar objects, vectors, strings, or svectors

For cases where args are numeric (integers, scalars, vectors), the arg values act as row or
column indices. Focusing on column functions, for example,
vector v1 = x.@col(3)
matrix m1 = x.@col(cid)

where X is a matrix and CID is a vector of column indices, and the two lines return the vec-
tor V1 and matrix M1 containing the 3rd column of X, and the columns of X referenced in
CID, respectively. Note that the elements of CID must be integers from 1 to the number of
columns of X.

For cases where args are strings (string literal, string object, svector), the arg values are
examined to find matches in the corresponding row or column labels . For example, the
commands
vector v2 = x.@col("apple")
matrix m2 = x.@col(scid)

where SCID is a svector of strings, produce the vector V2 and matrix M2 containing the 3rd
column of X, and the columns of X with labels that match the elements of SCID, respec-
tively. Note that all of the elements of SCID must be strings that match the column names
previously assigned to X.

You may mix the types of arg1 and arg2 in data member functions that take two arguments
so that, for example,
matrix m3 = x.@sub(3, "apple")

returns M3 containing the element of X in row 3 and column with label “apple”.

Similarly, the commands


matrix v1d = x.@dropcol(3)
matrix m1d = x.@dropcol(cid)
matrix v2d = x.@dropcol("apple")
matrix m2d = x.@dropcol(scid)
matrix m3d = x.@dropboth(5, "apple")

return the matrix objects

• V1D, the matrix X with column 3 dropped


• M1D, the matrix X with columns referenced by CID dropped
• V2D, the matrix X with the column with label “apple” dropped
Copying Data Between Objects—289

• M2D, the matrix X with the columns with labels in SCID dropped
• M3D, the matrix with the row 5 dropped and the column labeled “apple” dropped

The special symmetric matrix versions of these functions return syms:


sym sym1 = symorig.@sub(cid)
sym sym2 = symorig.@dropcol(3)
sym sym3 = symorig.@dropcol(cid)

return the sym objects

• SYM1, the columns (and corresponding rows) of SYMORIG referenced by CID


• SYM2, the contents of SYMORIG after dropping column and row 3
• V2D, the contents of SYMORIG after dropping columns and rows referenced by CID

Submatrix Extraction using Utility Functions


Combining matrix utility functions (“Initialize Using Creation Functions,” on page 283) with
the matrix extraction data members offers flexible methods for obtaining data from matrices.

Consider, for example, the extraction of multiple columns from the matrix X using the @col
data member function:
vector xid = @fill(1, 3, 5, 9)
matrix xsub = x.@col(xid)

extracts columns {1, 3, 5, 9} from the matrix X.

Since the args in the member data extraction functions may themselves be expressions, we
may combine the two lines into a single expression:
matrix xsub1 = x.@col(@fill(1, 3, 5, 9))

Similarly, extracting or dropping the 7 through 9th columns of X may be done using
matrix xsub2 = x.@col(@range(7, 9))
matrix xsub3 = x.@dropcol(@range(7, 9))

We can perform the same compound extractions in 2-dimensions, as in


matrix xsub4 = x.@sub(@range(3, 6), @sfill("apple", "orange"))
matrix xsub5 = x.@dropboth(4, @sfill("apple", "orange"))

which create XSUB4 containing rows 3 to 6 and columns with labels matching “apple” and
“orange” of X, and XSUB5 containing X after dropping row 4 and the columns with match-
ing labels.
290—Chapter 11.Copying Data Between Objects

Assigning to Part of a Matrix Objects


Data from a matrix may be assigned to part of another matrix object using the commands
colplace (p. 410), rowplace (p. 581), and matplace (p. 518). Consider the commands:
matrix(100,5) m1 = 0
matrix(100,2) m2 = 1
vector(100) v1 = 3
rowvector(100) v2 = 4
matplace(m1,m2,1,3)
colplace(m1,v1,3)
rowplace(m1,v2,80)

The matplace command places M2 in M1 beginning at row 1 and column 3. V1 is placed in


column 3 of M1, while V2 is placed in row 80 of M1.

You may combine matplace with @fill (p. 884) and the @row, @col, @droprow, or
@dropcol data members to perform complex subsetting and filling
matplace(z, x.@row(@fill(1, 3, 4)), 1, 1)

puts rows 1, 3, and 4 of the matrix X into the upper-left hand corner of Z. Note that Z must
be large enough to hold the X subset.

Copying Data Between Matrices and Series/Groups


The previous sections described techniques for copying data between matrix objects such as
vectors, matrices and scalars. In this section, we describe techniques for copying data
between matrix objects and workfile-based EViews objects such as series and groups.

Keep in mind that there are two primary differences between the ordinary series or group
objects and the matrix objects. First, operations involving series and groups use information
about the current workfile sample, while matrix objects do not. Second, there are important
differences in the handling of missing values (NAs) between the two types of objects.

Direct Assignment
The easiest method to copy data from series or group objects to a matrix object is to use
direct assignment. Place the destination matrix object on the left side of an equal sign, and
place the series or group to be converted on the right.

If you use a series object on the right-hand side and a vector on the left, EViews will only
use observations from the current sample to make the vector. If you place a group object on
the right and a matrix on the left, EViews will create a rectangular matrix out of the group
using observations from the current sample.
Copying Data Between Objects—291

While direct assignment is straightforward and convenient, there are two principal limita-
tions to the approach. First, EViews uses only the observations in the current sample when
copying the data. Second, observations containing missing data (NAs) for a series, or for
any series in the group, are dropped. Thus, if the current sample contains 20 observations,
but the series or group contains missing data, the dimension of the output vector or matrix
will be less than 20. (Below, we describe methods which allow you to override the current
sample and to retain missing values.)

Examples:
smpl 1963m03 1993m06
fetch hsf gmpyq
group mygrp hsf gmpyq
vector xvec = gmpyq
matrix xmat = mygrp

These statements create the vector XVEC and the two column matrix XMAT containing the
non-missing series and group data from 1963M03 to 1993M06. Note that if GMPYQ has a
missing value in 1970M01, and HSF contains a missing value in 1980M01, both observations
for both series will be excluded from XMAT.

When performing matrix assignment, you may refer to an element of a series, just as you
would refer to an element of a vector, by placing an index value in parentheses after the
name. An index value i refers to the i-th element of the series from the beginning of the
workfile range, not the current sample. For example, if the range of the current annual work-
file is 1961 to 1980, the expression GNP(6) refers to the 1966 value of GNP. These series ele-
ment expressions may be used in assigning specific series values to matrix elements, or to
assign matrix values to a specific series element. For example:
matrix(5,10) x
series yser = nrnd
x(1,1) = yser(4)
yser(5) = x(2,3)
yser(6) = 4000.2

assigns the fourth value of the series YSER to X(1,1), and assigns to the fifth and sixth val-
ues of YSER, the X(2,3) value and the scalar value “4000.2”, respectively.

While matrix assignments allow you to refer to elements of series as though they were ele-
ments of vectors, you cannot generally use series in place of vectors. Most vector and matrix
operations will error if you use a series in place of a vector. For example, you cannot perform
a rowplace command using a series name.

Furthermore, note that when you are not performing matrix assignment, a series name fol-
lowed by a number in parentheses will indicate that the lag/lead operator be applied to the
292—Chapter 11.Copying Data Between Objects

entire series. Thus, when used in generating series or in an equation, system, or model spec-
ification, GNP(6) refers to the sixth lead of the GNP series. To refer to specific elements of
the GNP series in these settings, you should use the @elem function.

Copy using @convert


The @convert (p. 764) function takes a series or group object and, optionally, a sample
object, and returns a vector or rectangular matrix. If no sample is provided, @convert will
use the workfile sample. The sample determines which series elements are included in the
matrix. Example:
smpl 61 90
group groupx inv gdp m1
vector v = @convert(gdp)
matrix x = @convert(groupx)

X is a 30  3 matrix with the first column containing data from INV, the second column
from GDP, and the third column from M1.

As with direct assignment, @convert excludes observations for which the series or any of
the series in the group contain missing data. If, in the example above, INV contains missing
observations in 1970 and 1980, V would be a 29 element vector while X would be a
28  3 matrix. This will cause errors in subsequent operations that require V and X to have
a common row dimension.

There are two primary advantages of using @convert over direct assignment. First, since
@convert is a function, it may be used in the middle of a matrix expression. Second, an
optional second argument allows you to specify a sample to be used in conversion. For
example:
sample s1.set 1950 1990
matrix x = @convert(grp, s1)
sym y = @inverse(@inner(@convert(grp, s1)))

performs the conversion using the sample defined in S1.

Copy using Commands


EViews also provides three useful commands that perform explicit conversions between
series and matrices with control over both the sample and the handling of NAs.

stom (p. 598) (Series TO Matrix) takes a series or group object and copies its data to a vec-
tor or matrix using either the current workfile sample, or the optionally specified sample. As
with direct assignment, the stom command excludes observations for which the series or
any of the series in the group contain missing data.

Example:
Matrix Expressions—293

sample smpl_cnvrt.set 1950 1995


smpl 1961 1990
group group1 gnp gdp money
vector(46) vec1
matrix(3,30) mat1
stom(gdp, vec1, smpl_cnvrt)
stom(group1, mat1)

While the operation of stom is similar to @convert, stom is a command and cannot be
included in a matrix expression. Furthermore, unlike @convert, the destination matrix or
vector must already exist and have the proper dimension.

stomna (p. 599) (Series TO Matrix with NAs) works identically to stom, but does not
exclude observations for which there are missing values. The elements of the series for the
relevant sample will map directly into the target vector or matrix. Thus,
smpl 1951 2000
vector(50) gvector
stom(gdp, gvector)

will always create a 50 element vector GVECTOR that contains the values of GDP from 1951
to 2000, including observations with NAs.

mtos (p. 522) (Matrix TO Series) takes a matrix or vector and copies its data into an existing
series or group, using the current workfile sample or a sample that you provide.

Example:
mtos(mat1, group1)
mtos(vec1, resid)
mtos(mat2, group1, smpl1)

As with stom the destination dimension given by the sample must match that of the source
vector or matrix.

Matrix Expressions
A matrix expression is an expression which combines matrix objects with mathematical
operators or relations, functions, and parentheses. While we discuss matrix functions in
great detail below, some examples will demonstrate the relevant concepts.

Examples:
@inner(@convert(grp, s1))
mat1*vec1
@inverse(mat1+mat2)*vec1
294—Chapter 11.Matrix Expressions

mat1 > mat2

EViews uses the following rules to determine the order in which the expression will be eval-
uated:
• You may nest any number of pairs of parentheses to clarify the order of operations in
a matrix expression.
• If you do not use parentheses, the operations are applied in the following order:
1. Unary negation operator and functions.
2. Multiplication and division operators.
3. Addition and subtraction operators.
4. Comparison operators: “>=”, “>”, “<=”, “<”, “<>”.

Examples:
@inverse(mat1+mat2)+@inverse(mat3+mat4)
vec1*@inverse(mat1+mat2)*@transpose(vec1)

In the first example, the matrices MAT1 and MAT2 will be added and then inverted. Simi-
larly the matrices MAT3 and MAT4 are added and then inverted. Finally, the two inverses
will be added together. In the second example, EViews first inverts MAT1+MAT2 and uses
the result to calculate a quadratic form with VEC1.

Matrix Operators
EViews provides standard mathematical operators for matrix objects.

(Note that element multiplication, division, inverse, and powers are not available using
operators, but are instead supported via functions).

Negation (–)
The unary minus changes the sign of every element of a matrix object, yielding a matrix or
vector of the same dimension. Example:
matrix jneg = -jpos

Addition (+)
You can add two matrix objects of the same type and size. The result is a matrix object of
the same type and size. Example:
matrix(3,4) a
matrix(3,4) b
matrix sum = a + b
Matrix Expressions—295

You can add a square matrix and a sym of the same dimension. The upper triangle of the
sym is taken to be equal to the lower triangle. Adding a scalar to a matrix object adds the
scalar value to each element of the matrix or vector object.

Subtraction (–)
The rules for subtraction are the same as the rules for addition. Example:
matrix(3,4) a
matrix(3,4) b
matrix dif = a - b

Subtracting a scalar object from a matrix object subtracts the scalar value from every ele-
ment of the matrix object.

Multiplication (*)
You can multiply two matrix objects if the number of columns of the first matrix is equal to
the number of rows of the second matrix.

Example:
matrix(5,9) a
matrix(9,22) b
matrix prod = a * b

In this example, PROD will have 5 rows and 22 columns.

One or both of the matrix objects can be a sym. Note that the product of two sym objects is
a matrix, not a sym. The @inner function will produce a sym by multiplying a matrix by its
own transpose.

You can premultiply a matrix or a sym by a vector if the number of columns of the matrix is
the same as the number of elements of the vector. The result is a vector whose dimension is
equal to the number of rows of the matrix.

Example:
matrix(5,9) mat
vector(9) vec
vector res = mat * vec

In this example, RES will have 5 elements.

You can premultiply a rowvector by a matrix or a sym if the number of elements of the
rowvector is the same as the number of rows of the matrix. The result is a rowvector whose
dimension is equal to the number of columns of the matrix.

Example:
296—Chapter 11.Matrix Expressions

rowvector rres
matrix(5,9) mat
rowvector(5) row
rres = row * mat

In this example, RRES will have 9 elements.

You can multiply a matrix object by a scalar. Each element of the original matrix is multi-
plied by the scalar. The result is a matrix object of the same type and dimensions as the orig-
inal matrix. The scalar can come before or after the matrix object. Examples:
matrix prod = 3.14159*orig
matrix xxx = d_mat*7

To perform element multiplication where you multiply every element of a matrix by very
element of another matrix, you should use the @emult (p. 869) function.

Division (/)
You can divide a matrix object by a scalar. Example:
matrix z = orig/3

Each element of the object ORIG will be divided by 3.

To perform element division where you divide every element of a matrix by very element of
another matrix, you should use the @ediv (p. 861) function.

Relational Operators (=, >, >=, <, <=, <>)


Two matrix objects of the same type and size may be compared using the comparison oper-
ators (=, >, >=, <, <=, <>). The result is a scalar logical value. Every pair of corre-
sponding elements is tested, and if any pair fails the test, the value 0 (FALSE) is returned;
otherwise, the value 1 (TRUE) is returned.

For example,
if result <> value then
run crect
endif

It is possible for a vector to be not greater than, not less than, and not equal to a second vec-
tor. For example:
vector(2) v1
vector(2) v2
v1(1) = 1
v1(2) = 2
v2(1) = 2
Matrix Commands and Functions—297

v2(2) = 1

Since the first element of V1 is smaller than the first element of V2, V1 is not greater than
V2. Since the second element of V1 is larger than the second element of V2, V1 is not less
than V2. The two vectors are not equal.

Matrix Commands and Functions


EViews provides a number of commands and functions that allow you to work with the con-
tents of your matrix objects. These commands and functions may be divided into roughly
four distinct types: (1) utility commands and functions, (2) element functions, (3) matrix
algebra functions, and (4) descriptive statistics functions.

Utility Commands and Functions


The utility commands and functions provide support for creating, manipulating, and assign-
ing values to your matrix objects. We have already seen a number of these commands and
functions, including the @convert (p. 764) function and the stom (p. 598) and stomna
(p. 599) commands, which convert data from series and groups into vectors and matrices,
as well as @vec (p. 1183), @vech (p. 1184), @rowextract (p. 1089), @columnextract
(p. 762), and matplace (p. 518).

A random sampling of other useful commands and functions include:


matrix a = @ones(10, 5)

which creates a 10  5 matrix of ones,


vector f = @getmaindiagonal(x)

which extracts the main diagonal from the square matrix X,


matrix g = @explode(sym01)

which creates a square matrix from the symmetric matrix object SYM01, and
matrix h1 = @resample(y)
matrix h2 = @permute(y)

which create matrices by randomly drawing (with replacement) from, and by permuting, the
rows of Y.

A listing of the matrix commands and functions is included in the matrix summary
in Chapter 15. “Matrix Language Summary,” on page 335.

Element Functions
EViews offers two types of functions that work with individual elements of a matrix object.
First, most of the element functions that may be used in series expressions can used with
298—Chapter 11.Matrix Commands and Functions

matrix objects. When used with a matrix object, these functions will return a similar object
whose elements are the values of a function evaluated at each element of the original.

For example, you may specify


matrix f = @log(y)

to compute the logarithm of each element of the matrix Y.

Similarly,
matrix tprob = @ctdist(x, df)

evaluates the cumulative distribution function value for the t-distribution for each element
of the matrix X and places the results in the corresponding cells of the matrix TPROB. Note
that DF may either be a scalar, or a matrix object of the same type and size as X.

See “Element Functions” on page 682 for summaries of the various element functions.

Second, EViews provides a set of element functions for performing element-by-element


matrix multiplication, division, inversion, and exponentiation. For example, to obtain a
matrix Z containing the inverse of every element in X, you may use:
matrix z = @einv(x)

Likewise, to compute the elementwise (Hadamard) product of the matrices A and B, you
may use
matrix ab = @emult(a, b)

The (i,j)-th element of the matrix AB will contain the product of the corresponding elements
of A and B: a ij  b ij .

See “Matrix Element Functions” on page 709 for additional detail.

Matrix Algebra Functions


The matrix algebra functions allow you to perform common matrix algebra operations.
Among other things, you can use these routines to compute eigenvalues, eigenvectors and
determinants of matrices, to invert matrices, to solve linear systems of equations, and to per-
form singular value decompositions.

For example, to compute the inner product of two vectors A and B, you may use
scalar ip = @inner(a, b)

To compute the Cholesky factorization of a symmetric matrix G,


matrix cf = @cholesky(g)

The least squares coefficient vector for the data matrix X and vector Y may be computed as
vector b = @inverse(@inner(x))*@transpose(x)*y
Matrix Commands and Functions—299

or
vector b = @solvesystem(@inner(x), @transpose(x)*y)

A listing of the matrix algebra functions and commands is included in “Matrix Command
Summary” on page 335 and “Matrix Algebra” on page 337.

Descriptive Statistics Functions


The descriptive statistics functions compute summary statistics for the data in the matrix
object. You can compute statistics such as the mean, median, minimum, maximum, and
variance, over all of the elements in your matrix.

For example,
scalar xmean = @mean(xmat)

computes the mean taken over all of the non-missing elements of the matrix XMAT, and
assigns the values to the scalar XMEAN. Similarly, the commands
scalar xquant95 = @quantile(xmat, .95)

computes the .95 quantile of the elements in XMAT.

Functions for computing descriptive statistics are discussed in “Basic Statistics” on


page 692.

In addition, there are functions for computing statistics for each column in a matrix.
vector xmeans = @cmean(xmat)

computes the mean for each column of XMAT and assigns the values to the vector XMEANS.
vector xmin = @cmin(xmat)

saves the column minimums in the vector XMIN. If, instead you wish to find the index of
the minimum element for the column, you may use @cimin instead:
vector ximin = @cimin(xmat)

The column statistics are outlined in “Matrix Column Statistics” on page 708.

Functions versus Commands


A function generally takes arguments, and always returns a result. Functions are easily iden-
tified by the initial “@” character in the function name.

There are two basic ways that you can use a function. First, you may assign the result to an
EViews object. This object may then be used in other EViews expressions, providing you
with access to the result in subsequent calculations. For example:
matrix y = @transpose(x)
300—Chapter 11.Matrix Commands and Functions

stores the transpose of matrix X in the matrix Y. Since Y is a standard EViews matrix, it may
be used in all of the usual expressions.

Second, you may use a function as part of a matrix expression. Since the function result is
used in-line, it will not be assigned to a named object, and will not be available for further
use. For example, the command:
scalar z = vec1*@inverse(v1+v2)*@transpose(vec1)

uses the results of the @inverse and @transpose functions in forming the scalar expres-
sion assigned to Z. These function results will not be available for subsequent computations.

By contrast, a command takes object names and expressions as arguments, and operates on
the named objects. Commands do not return a value.

Commands, which do not have a leading “@” character, must be issued alone on a line, and
may not be used as part of a matrix expression. For example, to convert a series X to a vector
V1, you would enter:
stom(x, v1)

Because the command does not return any values, it may not be used in a matrix expres-
sion.

NA Handling
As noted above, most of the methods of moving data from series and groups into matrix
objects will automatically drop observations containing missing values. It is still possible,
however, to encounter matrices which contain missing values.

For example, the automatic NA removal may be overridden using the stomna command.
Additionally, some of the element operators may generate missing values as a result of stan-
dard matrix operations. For example, taking element-by-element logarithms of a matrix
using @log will generate NAs for all cells containing nonpositive values.

EViews follows two simple rules for handling matrices that contain NAs. For all operators,
commands, and functions (with the exception of the descriptive statistics functions), EViews
works with the full matrix object, processing NAs as required. For descriptive statistic func-
tions, EViews automatically drops NAs when performing the calculation. These rules imply
the following:
• Matrix operators will generate NAs where appropriate. Adding together two matrices
that contain NAs will yield a matrix containing NAs in the corresponding cells. Multi-
plying two matrices will result in a matrix containing NAs in the appropriate rows and
columns.
Matrix Views and Procs—301

• All matrix algebra functions and commands will generate NAs, since these operations
are undefined. For example, the Cholesky factorization of a matrix that contains NAs
will contain NAs.
• All utility functions and commands will work as before, with NAs treated like any
other value. Copying the contents of a vector into a matrix using colplace (p. 410)
will place the contents, including NAs, into the target matrix.
• All of the matrix element functions will propagate NAs when appropriate. Taking the
absolute value of a matrix will yield a matrix containing absolute values for non-miss-
ing cells and NAs for cells that contain NAs.
• The descriptive statistics functions are based upon the non-missing subset of the ele-
ments in the matrix. You can always find out how many values were used in the com-
putations by using the @obs or the @nas functions.

Matrix Views and Procs


The individual object descriptions in the Object Reference list the various views and procs for
the various matrix objects. Listings are available for matrices (“Matrix,” on page 554), vec-
tors (“Vector,” on page 1221), symmetric matrices (“Sym,” on page 991), rowvectors
(“Rowvector,” on page 703), and coefs (“Coef” on page 22).

Matrix Graph and Statistics Views


All of the matrix objects, with the exception of the scalar object, have windows and views.
For example, you may display line and bar graphs for each column of the 10  5 matrix Z:
z.line
z.bar(p)

Each column will be plotted against the row number of the matrix.

Additionally, you can compute descriptive statistics for each column of a matrix, as well as
the correlation and covariance matrix between the columns of the matrix:
z.stats
z.cor
z.cov

By default, EViews performs listwise deletion by column when computing correlations and
covariances, so that each group of column statistics is computed using the largest possible
set of observations.

The full syntax for the commands to display and print these and other views is provided in
the reference for the specific object (e.g., matrix, sym) in the Object Reference.
302—Chapter 11.Matrix Views and Procs

Matrix Input and Output


EViews provides you with the ability to read and write files directly from matrix objects
using the import and export procedures.

Import
You may read directly into an EViews matrix object (matrix, vector, sym, etc.) from text
(both ASCII and binary), HTML, Excel XLSX, and Excel 97 XLS files. Excel reads includes
support for named ranges and multiple pages. The new engine supports a number of differ-
ent formats.

Excel Example
The command
matrix_name.import "c:\data files\data.xls"

loads the active sheet of DATA.XLSX into the MATRIX_NAME matrix object.
matrix_name.import "c:\data files\data.xls" range="GDP data"

reads the data contained in the “GDP data” sheet of “Data.XLS” into the MATRIX_NAME
object.

HTML Example
The command
mat1.import "c:\data.html"

loads into the MAT1 matrix object the data located in the HTML file “Data.HTML” located
on the C:\ drive
mat1.import(type=html) "http://www.tradingroom.com.au/apps/mkt/
forex.ac" colhead=3

loads into a matrix object MAT1 the data with the given URL located on the website site
“http://www.tradingroom.com.au”. The column header is set to three rows.

Text Example
The command
mat2.import c:\data.csv skip=5

reads “Data.CSV” into a MAT2, skipping the first 5 rows.


mat2.import(type=text) c:\date.txt delim=comma

loads the comma delimited data “Date.TXT” into the MAT2 matrix object.
Matrix Operations versus Loop Operations—303

Export
The export command supports a number of formats including the various ASCII, binary,
HTML, RTF, and Excel formats, along with LaTeX, Markdown, and PDF files. Importantly,
the Excel XLSX export allows you to write the matrix results into existing Excel files, begin-
ning at a specified cell.

The command:
matrix1.export mymatrix

exports the data in MATRIX1 to a CSV file named “mymatrix.CSV” in the default directory.
matrix1.export(h, t=csv, n="NaN") mymatrix

saves the contents of MATRIX1 along with the column and row headers to a CSV (comma
separated value) file named “mymatrix.CSV” and writes all NA values as “NaN”.
matrix1.export(h, t=html, s=50) mymatrix

exports the data in MATRIX1 along with the column and row headers to a HTML file named
“mymatrix.HTM” at half of the original size.
matrix1.exports(n=".", r=B) mymatrix

saves the data in the second column to a CSV file named “mymatrix.CSV”, and writes all NA
values as “.”.
matrix1.export(t=excelxml, cellfmt=clear, mode=update) mymatrix
range=Country!b5

writes the data in MATRIX1 to the preexisting “mymatrix.XLSX” Excel file to the “Country”
sheet at cell B5, where all cell formatting is cleared.

There are many more options for controlling reading and writing of matrix data; Chapter 5.
“Basic Data Handling,” on page 129 of User’s Guide I offers extensive discussion. See also
the descriptions for the matrix procs Matrix::import and Matrix::export (similar
descriptions are available for the other matrix objects.)

Matrix Operations versus Loop Operations


You may perform matrix operations using element operations and loops instead of the built-
in functions and commands. For example, the inner product of two vectors may be com-
puted by evaluating the vectors element-by-element:
scalar inprod1 = 0
for !i = 1 to @rows(vec1)
inprod1 = inprod1 + vec1(!i)*vec2(!i)
next

This approach will, however, generally be much slower than using the built-in function:
304—Chapter 11.Matrix Operations versus Loop Operations

scalar inprod2 = @inner(vec1, vec2)

You should use the built-in matrix operators rather than loop operators whenever you can.
The matrix operators are always much faster than the equivalent loop operations.

Similarly, suppose, for example, that you wish to subtract the column mean from each ele-
ment of a matrix. Such a calculation might be useful in constructing a fixed effects regres-
sion estimator. First, consider a slow method involving only loops and element operations:
matrix x = @convert(mygrp1)
scalar xsum
for !i = 1 to @columns(x)
xsum = 0
for !j = 1 to @rows(x)
xsum = xsum+x(!j,!i)
next
xsum = xsum/@rows(x)
for !j = 1 to @rows(x)
x(!j,!i) = x(!j,!i)-xsum
next
next

The loops are used to compute a mean for each column of data in X, and then to subtract
the value of the mean from each element of the column. A faster method for subtracting col-
umn means uses the built-in operators and functions:
matrix x = @convert(mygrp1)
vector xmean = @cmeans(x)
x = x - @scale(@ones(@rows(x), @columns(x)),@transpose(xmean))

The first line converts the data in MYGRP1 into the matrix X. The second line computes the
column means of X and saves the results in XMEAN. The last line subtracts the matrix of
column means from X. Note that we first create a temporary matrix of ones, then use the
@scale function to scale each column using the element in the corresponding column of the
transpose of XMEAN.
Chapter 12. Workfile Functions

EViews workfile functions provide information about each observation of a workfile based
on the structure of the workfile.

These functions may be viewed in two ways. First, they may be thought of as virtual series
available within each workfile that can be used wherever a regular series may be used.
Alternatively, they may be thought of as special functions that depend on two implicit argu-
ments: the workfile within which the function is being used, and the observation number
within this workfile for which to return a value.

Since workfile functions are based on the structure of a workfile, they may only be used in
operations where a workfile is involved. Workfile functions may be used in statements that
generate series in a workfile, in statements that set the workfile sample, and in expressions
used in estimating an equation using data in a workfile. These functions may not be used
when manipulating scalar variables or vectors and matrices in EViews programs.

Basic Workfile Information


The @obsnum function provides information on observation numbering for the workfile:
• @obsnum: returns the observation number of the current observation in the workfile.

The observation number starts at one for the first observation in the workfile, and incre-
ments by one for each subsequent observation.

For example:
series idnum = @obsnum

creates a series IDNUM that contains sequential values from one to the number of observa-
tions in the workfile.

Other functions return scalar values associated with the workfile and default workfile sam-
ple:
• @elem(x, "arg"): returns the value of the series x at observation or date arg. If the
workfile is undated, arg should be an integer corresponding to the observation ID as
given in @obsnum. If the workfile is dated, arg should be a string representation of a
date in the workfile. In both cases, the argument must be enclosed in double quotes.
Note that @elem is not available in panel structured workfiles.
• @ispanel: returns indicator for whether the workfile is panel structured (0 if no
workfile in memory).
• @obsrange: returns number of observations in the current active workfile range (0 if
no workfile in memory).
306—Chapter 12.Workfile Sample Information

• @obssmpl: returns number of observations in the current active workfile sample (0 if


no workfile in memory).
• @pagecount: returns the number of pages in the current active workfile (0 if no
workfile in memory)
• @pageexist: returns a 0 or 1 depending on whether the page specified by str exists in
the current workfile.

The following functions return a string value associated with the current workfile:
• @pagefreq: returns the frequency of the active page.
• @pagename: returns the name of the active page.
• @pagelist: returns a space delimited string containing the names of all the pages in
the current active workfile.
• @pagesmpl: returns the current sample for the active page.
• @pageids: returns the id series for the current active page. If the page is a regular
dated page, “@date” is returned. If the page is irregular, or structured by an id series,
names of the id series are returned. If the page is completely unstructured, empty
string is returned. In a panel it returns the cross-section identifiers followed by the
date identifier.
• @wfname: returns the current default workfile name.
• @wfpath: returns the current default workfile path.

Workfile Sample Information


Sample Index Functions
A key EViews feature is the ability to work with subsamples of observations. There are two
common ways of defining a subsample of observations in a workfile. One method is to spec-
ify a set of (0, 1) (boolean) identifiers that indicate whether each observation in the workfile
is included in the subsample. A second method is to specify a list of index values for the
observations in the subsample.

In some cases, working with the boolean indicators is more convenient. In others, especially
when the subsample is sparse and direct access to the observation is useful, working with
the index values may be preferred.

EViews provides workfile functions that allow you to extract information from the workfile
and workfile sample, and to convert between the two methods.
Workfile Sample Information—307

Current Sample Index (@pagesmplidx)


The @pagesmplidx function returns a vector object containing the index values for the
observations in the current sample.

Suppose we have an annual workfile from 2001 to 2024, and have set the workfile sample to
a subset of observations. The commands
wfcreate(wf=awf) a 2001 2024
smpl 2002 2003 2010 2011

create a workfile containing annual observations from 2001 to 2024, then sets the sample to
contain observations from 2002–2003 and 2010–2011. There are 24 observations in this work-
file which may be identified by index values 1 to 24. Then
vector ids = @pagesmplidx

will return IDS containing {2, 3, 10, 11}.

See @pagesmplidx (p. 1030).

Observations Index (@pageidx)


The @pageidx(arg) function returns a vector object containing the index values for the
observations in the workfile specified in arg.

The argument may be a vector of date numbers, an svector of date strings, or a string object
or string literal containing a space delimited list of dates.

Observation specifications that are outside of the workfile range will be ignored.

For example,
wfcreate(wf=qwf) q 2001 2024
vector id1 = @pageidx("2010q2 2010q3 2021q1 2023q4")

creates a workfile containing quarterly data from 2001 to 2024 and an ID1 vector containing
the values {38, 39, 81, 92}.

See @pageidx (p. 1027).

Boolean Indicators (@pageinidx)


The @pageinidx(arg) function, where arg is a vector containing observation index values,
returns a vector object, sized to match the workfile page length, that includes (0, 1) indica-
tors for each observation, with 1’s assigned to index elements in arg, and 0’s elsewhere.

If the arg contains index values that are outside of the workfile range, the function will
return an error.

If we have the commands


308—Chapter 12.Dated Workfile Information

vector id2 = @fill(10, 27, 30, 40)


vector incl = @pageinidx(id2)

then INC1 is a vector with 0’s everywhere except for the elements 10, 27, 30, and 40. Note
that these commands are a concise equivalent to the commands
vector inc2 = @zeros(@wfrange)
inc2(10) = 1
inc2(17) = 1
inc2(30) = 1
inc2(40) = 1

Using @pageidx to identify observation indices and then feeding the result to @pageinidx
offers a quick way of specifying a subsample of observations using dates:
wfcreate(wf=qwf) q 2001 2024
vector inc3 = @pageinidx(@pageidx("2010q2 2010q3 2021q1 2023q4")
stom(inc3, include_series)
smpl @all if include_series = 1

See @pageinidx (p. 1028).

Dated Workfile Information


Basic Date Functions
EViews offers a set of functions that provide information about the dates in your dated
workfiles. The first two functions return the start and end date of the period of time (inter-
val) associated with each observation in the workfile:
• @date: returns the start date of the period of time of each observation of the workfile.
• @enddate: returns the end date of the period of time associated with each observa-
tion of the workfile.

Each date is returned in a number using standard EViews date representation (fractional
days since 1st Jan A.D. 1; see “Dates,” beginning on page 104).

A period is considered to end during the last millisecond contained within the period. In a
regular frequency workfile, each period will end immediately before the start of the next
period. In an irregular workfile there may be gaps between the end of one period and the
start of the following period due to observations that were omitted in the workfile.

The @date and @enddate functions may be combined with EViews date manipulation func-
tions to provide a wide variety of calendar information about a dated workfile.

For example, if we had a monthly workfile containing sales data for a product, we might
expect the total sales that occurred in a given month to be related to the number of business
Dated Workfile Information—309

days (Mondays to Fridays) that occurred within the month. We could create a new series in
the workfile containing the number of business days in each month by using:
series busdays = @datediff(@date(+1), @date, "B")

If the workfile contained irregular data, we would need to use a more complicated expres-
sion since in this case we cannot assume that the start of the next period occurs immediately
after the end of the current period. For a monthly irregular file, we could use:
series busdays = @datediff(@dateadd(@date, 1, "M"), @date, "B")

Similarly, when working with a workfile containing daily share price data, we might be
interested in whether price volatility is different in the days surrounding a holiday for which
the market is closed. We may use the first formula given above to determine the number of
business days between adjacent observations in the workfile, then use this result to create
two dummy variables that indicate whether each observation is before or after a holiday
day.
series before_holiday = (busdays > 1)
series after_holiday = (busdays(-1) > 1)

We could then use these dummy variables as exogenous regressors in the variance equation
of a GARCH estimation to estimate the impact of holidays on price volatility.

In many cases, you may wish to transform the date numbers returned by @date so that the
information is contained in an alternate format. EViews provides workfile functions that
bundle common translations of date numbers to usable information. These functions
include:
• @year: returns the four digit year in which each observation begins. It is equivalent to
“@datepart(@date, "YYYY")”.
• @quarter: returns the quarter of the year in which each observation begins. It is
equivalent to “@datepart(@date, "Q")”.
• @month: returns the month of the year in which each observation begins. It is equiva-
lent to “@datepart(@date, "MM")”.
• @day: returns the day of the month in which each observation begins. It is equivalent
to “@datepart(@date, "DD")”.
• @weekday: returns the day of the week in which each observation begins, where
Monday is given the number 1 and Sunday is given the number 7. It is equivalent to
“@datepart(@date, "W")”.
• @hour: returns the hour associated with each observation as an integer. For example,
9:30AM returns 9, and 5:15PM returns 17.
• @minute: returns the minute associated with each observation as an integer. For
example, 9:30PM returns 30.
310—Chapter 12.Dated Workfile Information

• @second: returns the second associated with each observation as an integer.


• @hourf: returns the time associated with observation as a floating point hour. For
example, 9:30AM returns 9.5, and 5:15PM returns 17.25.
• @strdate(fmt): returns the set of observation dates as strings, using the date format
string fmt. See “Date Formats” on page 106 for a discussion of date format strings.
• @seas(season_number): returns dummy variables based on the period within the cur-
rent year in which each observation occurs, where the year is divided up according to
the workfile frequency. For example, in a quarterly file, “@seas(1)”, “@seas(2)”,
“@seas(3)”, and “@seas(4)” correspond to the set of dummy variables for the four
quarters of the year. these expressions are equivalent (in the quarterly workfile) to
“@quarter=1”, “@quarter=2”, “@quarter=3”, and “@quarter=4”, respectively.
• @isperiod(arg): returns dummy variables for whether each observation is in the
specified period, where arg is a double quoted date or period number. Note that in
dated workfiles, arg is rounded down to the workfile frequency prior to computation.

Additional information on working with dates is provided in “Dates,” beginning on


page 104.

Trend Functions
One common task in time series analysis is the creation of variables that represent time
trends. EViews provides two distinct functions for this purpose:
• @trend(["base_date"]): returns a time trend that increases by one for each observa-
tion of the workfile. The optional base_date may be provided to indicate the starting
date for the trend.
• @trendbr(["base_date"]): returns a time trend (with optional break point) that
increases by one for each observation of the workfile. The optional base_date may be
provided to indicate the starting date for the trend. Trend values before base_date will
be zero.
• @trendc(["base_date"]): returns a calendar time trend that increases based on the
number of calendar periods between successive observations. The optional base_date
may be provided to indicate the starting date for the trend.

The functions @trend and @trendc are used to represent two different types of time trends
that differ in some circumstances:
• In a regular frequency workfile, @trend and @trendc both return a simple trend that
increases by one for each observation of the workfile.
• In an irregular workfile, @trend provides an observation-based trend as before, but
@trendc now returns a calendar trend that increases based on the number of calen-
dar periods between adjacent observations. For example, in a daily irregular file
Dated Workfile Information—311

where a Thursday has been omitted because it was a holiday, the @trendc value
would increase by two between the Wednesday before and the Friday after the holi-
day, while the @trend will increase by only one.

Both @trend and @trendc functions may be used with an argument consisting of a string
containing the date at which the trend has the value of zero. If this argument is omitted, the
first observation in the workfile will be given the value of zero.

The choice of which type of time trend is appropriate in a particular context should be based
on what role the time trend is playing in the analysis. When used in estimation, a time trend
is usually used to represent some sort of omitted variable. If the omitted variable is some-
thing that continues to increase independently of whether the workfile data is observed or
not, then the appropriate trend would be the calendar trend. If the omitted variable is some-
thing that increases only during periods when the workfile data is observed, then the appro-
priate trend would be the observation trend.

An example of the former sort of variable would be where the trend is used to represent
population growth, which continues to increase whether, for example, financial markets are
open on a particular day or not. An example of the second sort of variable might be some
type of learning effect, where learning only occurs when the activity is actually undertaken.

Note that while these two trends are provided as built in functions, other types of trends
may also be generated based on the calendar data of the workfile. For example, in a file con-
taining monthly sales data, a trend based on either the number of days in the month or the
number of business days in the month might be more appropriate than a trend that incre-
ments by one for each observation.

These sorts of trends can be readily generated using @date and the @datediff functions.
For example, to generate a trend based on the number of days elapsed between the start date
of the current observation and the base date of 1st Jan 2000, we can use:
series daytrend = @datediff(@date, @dateval("1/1/2000"), "d")

When used in a monthly file, this series would provide a trend that adjusts for the fact that
some months contain more days than others.

Note that trends in panel structured workfiles follow special rules. See “Panel Trend Func-
tions” on page 320 for details.

Event Functions
These functions return information about each observation’s relationship with a specified
date, or date range:
312—Chapter 12.Dated Workfile Information

Basic Functions
• @daycount([“weekday_range”]): Returns the number of calendar days within each
observation of the workfile. The optional weekday_range argument lets you specify
certain days of the week to count.
If only one weekday is provided, @daycount returns the number of times that partic-
ular weekday occurs within the observation. If two weekdays are provided, @day-
count returns the number of times that any weekday between (and including) the
two weekdays occurs within the observation.
• @before("date"): returns a dummy variable with a value of 1 for each observation
prior to date, and zero for every other observation. If an observation is partially before
date (for example if you have a monthly workfile and specify a day as date), the frac-
tion of the observation before date is returned.
• @after("date"): returns a dummy variable with a value of 1 for each observation
after, and including, date, and zero for every other observation. If an observation is
partially before date (for example if you have a monthly workfile and specify a day as
date), the fraction of the observation after and including date is returned.
• @during("date1 date2"): returns a dummy variable with a value of 1 for each obser-
vation between date1 and date2 (inclusive), and zero for every other observation. If
an observation partially covers the specified dates (for example if you have a monthly
workfile and specify a pair of days in the same month), the fraction is returned.

Event Function
The event function returns a variable containing the proportion of a one-off event covered
by each observation. The event can be specified by a single date, or by a pair of dates to
denote a date range.
Syntax: @event("d1 [d2]"[, b])
d1: string
b: (optional) string
Return: series

where d1 and d2 are dates defining the one-off event specification and b is a basis specifica-
tion.

Returns the proportion or identifier of a one-off event covered by the observation, for each
observation in the workfile. If the workfile has a regular frequency and spans the entire
event, the returned series will sum to one over all observations. If the workfile is irregular or
does not span the entire event, the series may sum to less than one due to the observations
that have been omitted.
Dated Workfile Information—313

The optional basis parameter may be used to specify that only certain days of the week or
times of the day should be included as part of the holiday. This parameter has the format
"start_weekday-end_weekday[, start_time-end_time]"

e.g. “mon-thu” or “mon-sun,10am-4pm”.

@event is similar to the holiday functions below, but handles only a single non-repeating
date or date range and only the basis option.

Holiday Functions
The @holiday and @holidayset functions allow you to analyze and account for different
behavior on holiday days, around the world. These functions may be used to create series
that indicate the proportion of an annual event covered by each observation.

The @holiday function returns the proportion or identifier of an annual event covered by
the observation, for each observation in the workfile.

The basic syntax for the holiday function is


Syntax: @holiday(h[, b][, flag...])
h: string
b: string
flag: (optional) string
Return: series

where h is the holiday event specification, b is a basis specification, and flag is a calculation
scaling flag.

@holiday is similar to @holidayset, but allows for the specification of holidays using a
range pair of dates, while disallowing multiple holiday event specifications.

The @holidayset function returns the proportion or identifier of multiple annual events
covered by the observation, for each observation in the workfile.

The basic syntax for the holiday set function is


Syntax: @holidayset(h[, b][, flag...])
h: string
b: string
flag: (optional) string
Return: series

where h is one or more holiday event specifications, b is a basis specification, and flag is a
calculation scaling flag.
314—Chapter 12.Dated Workfile Information

Event Specification
The h specification identifies holiday events using date specifications of the form:
"base[~|!][(offset)][[weights]]"
where the base component consists of a single date, a pair of dates (forming a range), or a
single or a named group of holidays:
• A single date consists of either a day-of-the-month specification (e.g., “Dec25”), an
n-th-weekday-of-the-month specification (e.g., “Nov4Thu” for the fourth Thursday in
November or “May-1Mon” for the l Monday in May), or a named holiday (“Named
Holidays,” on page 314).
• Multiple dates may be specified using a date range (e.g., “Dec25 Jan05”,
“Nov4Thu May-1Mon”), or a named group of holidays (“Named Groups,” on
page 315).

The remainder of the specification consists of optional settings. The base component speci-
fication may be followed by any of the following options:
• a weekend modifier (“Modifiers,” on page 316).
• a parenthetical offset (“Offsets,” on page 316).
• a bracketed list of weights (“Weights,” on page 316).

For a base consisting of a range pair of dates, optional settings may be provided for both the
start and end dates.

For a base consisting of a named group, the optional settings will be applied to each of the
individual members of the group.

Named Holidays
EViews supports named holidays for common holidays in the G8 countries, including the
following ecclesiastical holidays: “epiphany”, “easterfriday”, “goodfriday”, “easter”, “easter-
monday”, “ascension”, “pentecost”, “whitmonday”, “assumption”, “allsaints”, “immacu-
late”, “christmas”, “saintstephen.

Also available are New Years Day (“nyd”, “newyear”, and “newyears”), Lunar New Year
(“cny”, “lny”, and “lunarnewyear”), International Women’s Day (“women” and “wom-
ens”), and International Men’s Day (“men” and “mens”).

Named holidays primarily associated with a specific country are suffixed with a locale code
following ISO 3166-1 alpha-2, i.e., the Internet country codes for top-level domains such as
“.ca” and “.de”. These named holidays are:
• Canada – “victoria.ca”, “canada”, “civic.ca”, “labour.ca”, “thanksgiving.ca”
(also“thanks.ca”), “remembrance.ca”, “boxing.ca”
Dated Workfile Information—315

• France – “labour.fr”, “victory.fr”, “bastille.fr”, “armistice.fr”


• Germany – “labour.de”, “unity.de”
• Italy – “liberation.it”, “labour.it”, “republic.it”
• Russia – “christmas.ru”, “defender.ru”, “springlabour.ru”, “victory.ru”, “russia”,
“unity.ru”
• United Kingdom – “mayday.uk”, “springbank.uk”, “summerbank.uk”, “boxing.uk”
• United States of America – “mlk.us”, “presidents.us”, “memorial.us”, “indepen-
dence.us”, “labor.us”, “columbus.us”, “veterans.us”, “thanksgiving” (also “thanks”)

Note that the named holidays “canada”, “russia”, and “thanksgiving” do not include a suf-
fix, either to avoid redundancy or maintain compatibility with earlier versions of EViews.
Also note that “christmas.ru” is included to reflect the Russian Orthodox Church’s use of the
Julian calendar.

In general, a suffix may be safely added to any named holiday that does not already include
one, e.g. “christmas.us” or “nyd.it”. Unless noted above, such combinations do not alter the
nominal date of the holiday but may produce different results when combined with a week-
end modifier (“Modifiers,” on page 316).

Named Groups
Named groups are preset collections of holidays. EViews currently supports a single named
group, “bank”, for each of the supported locales, i.e., “bank.ca”, “bank.fr”, “bank.de”, etc.,
allowing easy access to the common bank holidays.

The membership of these groups are:


• Canada, “bank.ca” – “nyd goodfriday victoria canada civic labour thanksgiving
remembrance christmas boxing”
• France, “bank.fr” –“ nyd eastermonday labour victory ascension whitmonday bastille
assumption allsaints armistice christmas”
• Germany, “bank.de” – “nyd goodfriday eastermonday labour ascension whitmonday
unity christmas saintstephen”
• Italy, “bank.it” – “nyd epiphany easter eastermonday liberation labour republic
assumption allsaints immaculate christmas saintstephen”
• Russia, “bank.ru” – “nyd christmas defender womens springlabour victory russia
unity”
• United Kingdom, “bank.uk” – “nyd goodfriday eastermonday mayday springbank
summerbank christmas boxing”
316—Chapter 12.Dated Workfile Information

• United States of America, “bank.us” – “nyd mlk presidents memorial independence


labor columbus veterans thanksgiving christmas”

All named group members have an implied suffix matching the group’s suffix. When using a
named group, the sum of proportion values within a year will equal the number of group
members (ignoring sample effects).

Modifiers
A weekend modifier character “~” or “!” indicates special handling of dates that fall on
weekends.
• If “~” is used, then the date will be adjusted to the nearest weekday. A date landing
on a Saturday is adjusted to the preceding Friday, and a date landing on a Sunday is
adjusted to the following Monday.
• If “!” is used with a named holiday, then a more sophisticated set of rules is used to
determine when the holiday will be observed, reflecting public holiday and bank hol-
iday conventions.

In some locales, holidays are observed according to the simple rule encapsulated by the “~”
modifier and thus the two modifiers will behave identically. For example, suppose we are
evaluating “christmas.us!” for the year 2021. That date lands on a Saturday and the holiday
will be observed on the preceding Friday, Dec. 24. However, if evaluating “christmas.uk!”
for the same year, weekend holidays are observed on the nearest following weekday in this
locale, thus the holiday will be observed on Monday, Dec. 27. Similarly, “boxing.uk!” will be
observed on Tuesday, Dec. 28.

Offsets
A date followed by a parenthetical offset will be adjusted by the given number of days. For
example, “christmas(-1)” could be used to specify Christmas Eve. If a weekend modifier is
also present, e.g. “christmas~(-1)”, the offset is applied after any adjustment made by the
modifier.

Basis
The optional basis parameter may be used to specify that only certain days of the week or
times of the day should be included as part of the holiday. This parameter has the format
"start_weekday-end_weekday[, start_time-end_time]"

e.g. “mon-thu” or “mon-sun,10am-4pm”.

Weights
A date followed by a bracketed list of weights is considered to occur over multiple days. The
specified weights determine the relative proportion of the holiday occurring on each day,
with the sum of proportions across all days within a year equaling one. The list must contain
Dated Workfile Information—317

an odd number of terms, with the middle term corresponding to the nominal date of the hol-
iday (after adjustment from any weekend modifier or offset).

For example, evaluating “christmas” for a daily workfile would return the value 1 for the
observation on Dec. 25 and the value 0 for all other observations in that year. Evaluating
“christmas[1,2,1]” would return the value 0.25 for the observation on Dec. 24, the value 0.5
for Dec. 25, and the value 0.25 for Dec. 26, returning the value 0 for all other observations.

Several named weight patterns are available as alternatives to explicit weight lists:
• “rampup(n)” – An increasing integer sequence of length n ending on the date. For
example, “[rampup(3)]” is equivalent to “[1,2,3,0,0]”.
• “rampdown(n)” – A decreasing integer sequence of length n beginning on the date.
For example, “[rampdown(3)]” is equivalent to “[0,0,3,2,1]”.
• “ramp(n)” –An increasing and then decreasing integer sequence centered on the date.
For example, “[ramp(3)]” is equivalent to “[1,2,3,2,1]”.

Note that weights may not be included when a pair of dates is used to specify a range in
@holiday.

Flag
The optional flag parameter supports two options, “binary” and “denorm”.
• If “binary” is specified, any non-zero value that would be returned by @holiday is
replaced by one, thus forcing the function to return only zeros and ones. This flag is
equivalent to the expression “@holiday(...)>0”.
• If “denorm” is specified, then the default normalization steps for weighted dates
(dividing by the sum of weights) and sets or groups of holidays (dividing by the num-
ber of distinct holidays) are not performed.

For example, @holiday("christmas[1,2,1]") returns values 0.25, 0.5, and 0.25 on


sequential observations, whereas @holiday("christmas[1,2,1]", "denorm") would
return values 1, 2, and 1.

@holiday Examples
The command
series jan1 = @holiday("Jan1")

generates a series containing a non-zero value only for those observations associated with
January 1st. For a daily or lower frequency workfile, only a single observation will cover
January 1st each year and that observation will have a value of 1. For a higher frequency
workfile, multiple observations will cover January 1st and thus have a value less than one.
For example, in an intra-day workfile with a frequency of six hours, each of the four obser-
vations for January 1st every year will have the value 0.25.
318—Chapter 12.Dated Workfile Information

series jan1early = @holiday("Jan1", "Mon-Sun,9AM-2PM")

generates a series that is non-zero only for those observations associated with January 1st
and between the hours of 9AM (inclusive) and 3PM (exclusive). For an intra-day workfile
with a frequency of six hours, the two observations for January 1st that begin at 6AM and
noon each year will have the value 0.5. Note that the end time of the basis specification, e.g.
2PM, is considered to extend to the last moment of the specified time, thus 2PM is inter-
preted as 2:59:59.999PM (3PM rather than 2PM).
series mondays = @holiday("Nov1Mon(1)")

generates a series that is non-zero only for those observations that fall on the day after the
first Monday in November, i.e. the Tuesday that is US federal Election Day.
series frenchlabor = @holiday("Labour.fr~")

Generates a series that is non-zero only for those observations associated with French Labor
Day (May 1st). Should that day fall on a Saturday, the observation(s) for the preceding Fri-
day will be non-zero instead, or if that day falls on a Sunday, the observation(s) for the fol-
lowing Monday will be non-zero. For example, in a daily workfile covering years 2020
through 2024, the observations for Friday May 1 2020, Friday April 30 2021, Monday May 2
2022, Monday May 1 2023, and Wednesday May 1 2024 would have the value 1.
series canadaday = @holiday("Canada!")

generates a series that is non-zero only for those observations associated with Canada Day
(July 1st). Should that day fall on a Saturday or a Sunday, the observation(s) for the follow-
ing Monday will be non-zero instead. For example, in a daily workfile covering years 2022
through 2024, the observations for Friday July 1 2022, Monday July 3 2023, and Monday
July 1 2024 would have the value 1.
series lunar = @holiday("LNY~(-3)")

generates a series that is non-zero only for those observations occurring three days before
the Lunar New Year, adjusted for weekends. For example, in a daily workfile covering year
2020, while the nominal date for the holiday is Saturday January 25, the observation for
Tuesday January 21 would have the value 1 as a consequence of the weekend modifier and
offset.
series newyears1 = @holiday("NewYears[1,2,0]")

generates a series that is non-zero only for those observations associated with New Year's
Day (January 1st) and the preceding day (December 31st). In the common case where those
two days will be covered by different observations, the observation for December 31st will
have the value 0.33 and the observation for January 1st will have the value 0.67 given the
relative weights specified.
series newyears2 = @holiday("NewYears[1,2,0]","denorm")
Dated Workfile Information—319

generates a series that is non-zero only for those observations associated with New Year's
Day (January 1st) and the preceding day (December 31st). With the use of the “denorm”
option, the observation for December 31st will have the value 1 and the observation for Jan-
uary 1st will have the value 2.
series ukbank = @holiday("Bank.uk!")

generates a series that is non-zero only for those observations associated with United King-
dom bank holidays included in the “bank.uk” named group. The weekend modifier “!” is
applied to each individual holiday in the group.
series postvets = @holiday("Veterans.us(7) Thanksgiving.us")

generates a series that is non-zero only for those observations between a week after US Vet-
erans Day and US Thanksgiving. This range normally covers between five to eleven days,
depending on the year. For example, in 2020 this range covers nine days (November 18
through November 26), thus in daily workfile the observations associated with those days
would have the value 0.111.

@holidayset Examples
The command
series jan1set = @holidayset("Jan1")

generates a series containing a non-zero value only for those observations associated with
January 1st. For a daily or lower frequency workfile, only a single observation will cover
January 1st each year and that observation will have a value of 1. For a higher frequency
workfile, multiple observations will cover January 1st and thus have a value less than one.
For example, in an intra-day workfile with a frequency of six hours, each of the four obser-
vations for January 1st every year will have the value 0.25. Since only a single holiday is
specified, this function behaves identically to @holiday.
series vetsset = @holidayset("Veterans.us(7) Thanksgiving.us")

generates a series that is non-zero only for those observations a week after US Veterans Day
and on US Thanksgiving. For example, in 2020 the two holidays occur on November 18 and
November 26, thus in daily workfile the observations associated with those days would each
have the value 0.5. Note that unlike the @holiday function, the two holidays included are
distinct and do not specify a range.
series easterset = @holidayset("Easter Unity.de[ramp(3)] Oct31~")

generates a series that is non-zero only for those observations associated with Easter, the
five days on and around German Unity Day, and Halloween, adjusted for weekends. For
example, in a daily workfile covering year 2020, the observation for Sunday April 12 will
have the value 0.333, the observations for Thursday October 1 through Monday October 5
will have the values 0.037, 0.074, 0.111, 0.074, and 0.037, respectively, and finally the obser-
vation for Friday October 30 will have the value 0.333.
320—Chapter 12.Panel Workfile Functions

Indicator Functions
These functions produce indicators for whether each observation satisfies a specific condi-
tion:
• @inlist(series, “list”): returns a dummy variable with a value of 1 for each observa-
tion of series equal to one of the values specified in list. list should be a quoted, space
delimited list of values. For example, @inlist(name, “John Jack Susan”)
returns a dummy variable equal to 1 for each observation where name matches either
“John”, “Jack” or “Susan”.
• @between(series, val1, val2): returns dummy variable equal to 1 for observations
where series is greater than or equal to val1 and less than or equal to val2. For exam-
ple, @between(X, 0.4, 0.6) returns a dummy variable equal to 1 for each observa-
tion of X satisfying 0.4  X  0.6 .

Panel Workfile Functions


Panel Identifier Functions
Additional information is available in panel structured workfiles. EViews provides workfile
functions that provide information about the cross-section, cell, and observation IDs associ-
ated with each observation in a panel workfile:
• @crossid: returns the cross-section index (cross-section number) of each observa-
tion.
• @cellid: returns the inner dimension index value for each observation. The index
numbers identify the unique values of the inner dimension observed across all cross-
sections. Thus, if the first cross-section has annual observations for 1990, 1992, 1994,
and 1995, and the second cross-section has observations for 1990, 1995, and 1997,
the corresponding @cellid values will be (1, 2, 3, 4) and (1, 4, 5), respectively.
• @obsid: returns the observation number within each panel cross section for each
observation. @obsid is similar to @obsnum except that it resets to one whenever it
crosses the seam between two adjacent cross sections.

See “Identifier Indices” on page 2308 of the User’s Guide II for additional discussion.

Panel Trend Functions


Central to the notion of a panel trend is the notion that the trend values are initialized at the
start of a cross-section, increase for successive observations in the specific cross-section, and
are reset at the start of the next-cross section.
Panel Workfile Functions—321

Beyond that, there are several notions of a time trend that may be employed. EViews pro-
vides four different functions that may be used to create a trend series: @obsid, @trendc,
@cellid, and @trend.

The @obsid function may be used to obtain the simplest notion of a trend in which the val-
ues for each cross-section begin at one and increase by one for successive observations in
the cross-section. To begin your trends at zero, simply use the expression “@OBSID-1”. Note
that such a trend does not use information about the cell ID values in determining the value
increment.

The calendar trend function, @trendc, computes trends in which values for observations
with the earliest observed date are normalized to zero, and successive observations are
incremented based on the calendar for the workfile frequency.

Lastly, @cellid and @trend compute trends using the observed dates in the panel:
• @cellid, which returns an index into the unique values of the cell ID, returns a form
of time trend in which the values increase based on the number of cell ID values
between successive observations.
• @trend function is equivalent to “@cellid-1”.

In fully balanced workfiles (workfiles with the same set of cell identifier in each cross-sec-
tion), the expressions “@obsid-1”, “@cellid-1”, and “@trend” all return the same values.
Additionally, if the workfile follows a regular frequency, then the @trendc function returns
the same values as @trend.

Note that because of the way they employ information computed across cross-sections,
@trend and @trendc may not take the optional base_date argument in panel structured
workfiles (see “Trend Functions” on page 310).
322—Chapter 12.Panel Workfile Functions
Chapter 13. Special Expression Reference

The following reference is an alphabetical listing of special expressions that may be used in
series assignment and generation, or as terms in estimation specifications.

Special Expression Summary


ar..........................autoregressive error specification (p. 323).
d...........................fractional difference specification (p. 324).
@expand ..............automatic dummy variables (p. 325).
ma ........................moving average error specification (p. 326).
na .........................not available (missing value) code (p. 327).
pdl ........................polynomial distributed lag specification (p. 328).
sar ........................seasonal autoregressive error specification (p. 329).
sma.......................seasonal moving average error specification (p. 329).

Special Expressions
The following section provides an alphabetical listing of the commands and functions asso-
ciated with the EViews programming language. Each entry outlines the basic syntax and
provides examples and cross references.

ar Special Expression

Autoregressive error specification.


Syntax: @ar(arg)
arg: integer or lag range

The AR specification can appear in an ls (p. 181) or tsls (p. 612) specification to indicate
an autoregressive component. ar(1) indicates the first order component, ar(2) indicates
the second order component, and so on.

You may express a range of AR terms using the “to” keyword between a starting and ending
integer.

Examples
The command:
ls m1 c tb3 tb3(-1) ar(1) ar(4)
324—Chapter 13.Special Expression Reference

regresses M1 on a constant, TB3, and TB3 lagged once with a first order and fourth order
autoregressive component. The command:
tsls sale c adv ar(1) ar(2) ar(3) ar(4) @ c gdp

performs two-stage least squares of SALE on a constant and ADV with up to fourth order
autoregressive components using a constant and GDP as instruments.
tsls sale c adv ar(1 to 4) @ c gdp

estimates an equivalent specification.

Cross-references
See Chapter 24. “Time Series Regression,” on page 1127 of User’s Guide II for details on
ARMA and seasonal ARMA modeling.

See also sar (p. 329), ma (p. 326), and sma (p. 329).

d Special Expression

Fractional difference specification.

The D specification can appear in an ls (p. 181) equation specification to indicate that the
equation should be estimated with fractional differencing (typically as part of an ARFIMA
model).

Examples
The command:
ls m1 c tb3 tb3(-1) ar(1) ar(4) d

regresses M1 on a constant, TB3, and TB3 lagged once with a first order and fourth order
autoregressive component and fractional differencing.

Cross-references
See Chapter 24. “Time Series Regression,” on page 1127 of User’s Guide II for details on
ARMA and seasonal ARMA modeling.

See also sar (p. 329), ma (p. 326), and sma (p. 329).
@expand—325

@expand Special Expression

Automatic dummy variables.

Create a set of dummy variables that span the unique values of the input series
Syntax: @expand(ser1[, ser2, ser3, ...][, drop_spec])
ser1: series, alpha
ser2...: series, alpha

The @expand expression may be added in estimation to indicate the use of one or more
automatically created dummy variables.

The optional drop_spec may be used to drop one or more of the dummy variables. drop_spec
may contain the keyword @dropfirst (indicating that you wish to drop the first category),
@droplast (to drop the last category), or a description of an explicit category, using the syn-
tax:
@drop(val1[, val2, val3,...])

where each argument corresponds to a category in @expand. You may use the wild card “*”
to indicate all values of a corresponding category.

Example
For example, consider the following two variables:
• SEX is a numeric series which takes the values 1 and 0.
• REGION is an alpha series which takes the values “North”, “South”, “East”, and
“West”.

The command:
eq.ls income @expand(sex) age

regresses INCOME on two dummy variables, one for “SEX=0” and one for “SEX=1” as well
as the simple regressor AGE.

The @EXPAND statement in,


eq.ls income @expand(sex, region) age

creates 8 dummy variables corresponding to:


sex=0, region="North"
sex=0, region="South"
sex=0, region="East"
sex=0, region="West"
326—Chapter 13.Special Expression Reference

sex=1, region="North"
sex=1, region="South"
sex=1, region="East"
sex=1, region="West"

The expression:
@expand(sex, region, @dropfirst)

creates the set of dummy variables defined above, but no dummy is created for “SEX=0,
REGION="North"”. In the expression:
@expand(sex, region, @droplast)

no dummy is created for “SEX=1, REGION="WEST"”.

The expression:
@expand(sex, region, @drop(0,"West"), @drop(1,"North"))

creates a set of dummy variables from SEX and REGION pairs, but no dummy is created for
“SEX=0, REGION="West"” and “SEX=1, REGION="North"”.
@expand(sex, region, @drop(1,*))

specifies that dummy variables for all values of REGION where “SEX=1” should be
dropped.
eq.ls income @expand(sex)*age

regresses INCOME on regressor AGE with category specific slopes, one for “SEX=0” and
one for “SEX=1”.

Cross-references
See “Automatic Categorical Dummy Variables” on page 1035 of User’s Guide II for further
discussion. See also @wexpand (p. 1192).

ma Special Expression

Moving average error specification.

The ma specification may be added in an ls (p. 181) or tsls (p. 612) specification to indi-
cate a moving average error component. ma(1) indicates the first order component, ma(2)
indicates the second order component, and so on.

You may express a range of MA terms using the “to” keyword between a starting and ending
integer.
na—327

Examples
ls(z) m1 c tb3 tb3(-1) ma(1) ma(2)

regresses M1 on a constant, TB3, and TB3 lagged once with first order and second order
moving average error components. The “z” option turns off backcasting in estimation.
ls(z) m1 c tb3 tb3(-1) ma(1 to 4)

estimates the same model but with MA terms from 1 to 4.

Cross-references
See “Time Series Regression” on page 1127 of User’s Guide II for details on ARMA and sea-
sonal ARMA modeling.

See also sma (p. 329), ar (p. 323), and sar (p. 329).

na Special Expression

Not available code. “NA” is used to represent missing observations.

Examples
smpl if y >= 0
series z = y
smpl if y < 0
z = na

generates a series Z containing the contents of Y, but with all negative values of Y set to
“NA”.

NA values will also be generated by mathematical operations that are undefined:


series y = nrnd
y = log(y)

will replace all positive value of Y with log(Y) and all negative values with “NA”.
series test = (yt <> na)

creates the series TEST which takes the value one for nonmissing observations of the series
YT. A zero value of TEST indicates missing values of the series YT.

Note that the behavior of missing values has changed since EViews 2. Previously, NA values
were coded as 1e-37. This implied that in EViews 2, you could use the expression:
series z = (y>=0)*x + (y<0)*na

to return the value of Y for non-negative values of Y and “NA” for negative values of Y. This
expression will now generate the value “NA” for all values of Y, since mathematical expres-
328—Chapter 13.Special Expression Reference

sions involving missing values always return “NA”. You must now use the smpl statement as
in the first example above, or the @recode or @nan function.

Cross-references
See “Missing Values” on page 203 of User’s Guide I for a discussion of working with missing
values in EViews.

pdl Special Expression

Polynomial distributed lag specification.

This expression allows you to estimate polynomial distributed lag specifications in ls or


tsls estimation. pdl forces the coefficients of a distributed lag to lie on a polynomial. The
expression can only be used in estimation by list.

Syntax
pdl(series_name, lags, order[,options])

Options
The PDL specification must be provided in parentheses after the keyword pdl in the follow-
ing order: the name of the series to which to fit a polynomial lag, the number of lags to
include, the order (degree) of polynomial to fit, and an option number to constrain the PDL.
By default, EViews does not constrain the endpoints of the PDL.

The constraint options are:


1 Constrain the near end of the distribution to zero.
2 Constrain the far end of the distribution to zero.
3 Constrain both the near and far end of the distribution
to zero.

Examples
ls sale c pdl(order,8,3) ar(1) ar(2)

fits a third degree polynomial to the coefficients of eight lags of the regressor ORDER.
tsls sale c pdl(order,12,3,2) @ c pdl(rain,12,6)

fits a third degree polynomial to the coefficients of twelve lags of ORDER, constraining the
far end to be zero. Estimation is by two-stage least squares, using a constant and a sixth
degree polynomial fit to twelve lags of RAIN.
tsls y c x1 x2 pdl(z,12,3,2) @ c pdl(*) z2 z3 z4
sma—329

When the PDL variable is exogenous in 2SLS, you may use “pdl(*)” in the instrument list
instead of repeating the full PDL specification.

Cross-references
See “Polynomial Distributed Lags (PDLs)” on page 1029 of User’s Guide II for further discus-
sion.

sar Special Expression

Seasonal autoregressive error specification.

sar can be included in ls or tsls specification to specify a multiplicative seasonal autore-


gressive term. A sar(p) term can be included in your equation specification to represent a
seasonal autoregressive term with lag p . The lag polynomial used in estimation is the prod-
uct of that specified by the ar terms and that specified by the sar terms. The purpose of the
sar expression is to allow you to form the product of lag polynomials.

Examples
ls tb3 c ar(1) ar(2) sar(4)

TB3 is modeled as a second order autoregressive process with a multiplicative seasonal


autoregressive term at lag four.
tsls sale c adv ar(1) sar(12) sar(24) @ c gdp

In this two-stage least squares specification, the error term is a first order autoregressive pro-
cess with multiplicative seasonal autoregressive terms at lags 12 and 24.

Cross-references
See “Background,” beginning on page 1127 of User’s Guide II for details on ARMA and sea-
sonal ARMA modeling.

See also sma (p. 329), ar (p. 323), and ma (p. 326).

sma Special Expression

Seasonal moving average error specification.

sma can be included in a ls or tsls specification to specify a multiplicative seasonal mov-


ing average term. A sma(p) term can be included in your equation specification to represent
a seasonal moving average term of order p . The lag polynomial used in estimation is the
product of that specified by the ma terms and that specified by the sma terms. The purpose
of the sma expression is to allow you to form the product of lag polynomials.
330—Chapter 13.Special Expression Reference

Examples
ls tb3 c ma(1) ma(2) sma(4)

TB3 is modeled as a second order moving average process with a multiplicative seasonal
moving average term at lag four.
tsls(z) sale c adv ma(1) sma(12) sma(24) @ c gdp

In this two-stage least squares specification, the error term is a first order moving average
process with multiplicative seasonal moving average terms at lags 12 and 24. The “z” option
turns off backcasting.

Cross-references
See “Background,” beginning on page 1127 of User’s Guide II for details on ARMA and sea-
sonal ARMA modeling.

See also sar (p. 329), ar (p. 323), and ma (p. 326).
Chapter 14. String and Date Summary

EViews provides a full library of string and date functions for use with alphanumeric and
date values. The following is a summary listing of the functions for working with these val-
ues.

Chapter 5. “Strings and Dates,” on page 85 contains a discussion of the use of strings and
dates in EViews, and provides a additional detail on some of the more commonly employed
string and date functions.

String Function Summary


@addquotes ..........Enclose string in quotation marks (p. 715).
@asc.....................ASCII value of character (p. 717).
@chr ....................ASCII value to string character (p. 744).
@iif ......................Recode values by condition (conditional value) (p. 915).
@inlist..................Dummy variable for value in list (p. 921).
@insert.................Insert string into string (p. 923).
@instr ..................Find position of substring in a string (p. 924).
@left ....................Left-hand characters in a string (p. 942).
@len.....................Length of a string (p. 943).
@length................Length of a string (p. 944).
@lower.................Lowercase representation of a string, or lower triangular matrix of a
matrix (p. 951).
@ltrim ..................Trim left-whitespace from string (p. 953).
@mid ...................Substring in middle or from middle to end of string (p. 974).
@nan....................Recode missing values (p. 1009).
@recode ...............Recode value by condition (p. 1068).
@replace...............Replace substring in string (p. 1070).
@right ..................Right substring of string (p. 1075).
@rinstr .................Find substring position in string (p. 1078).
@rtrim..................Trim right whitespace of string (p. 1100).
@str .....................String representation of number (p. 1123).
@strdate ...............String corresponding to the date of the observation (p. 1128).
@stripcommas ......Remove leading and trailing commas surrounding string (p. 1129).
@stripparens.........Remove paired leading and trailing parentheses surrounding string
(p. 1130).
332—Chapter 14.String Function Summary

@stripquotes ........ Remove paired double-quotation marks surrounding string


(p. 1131).
@strlen ................ Length of string (p. 1132).
@trim .................. Trim left and right whitespace from string (p. 1153).
@upper ................ Uppercase representation of a string; or upper triangular matrix of a
matrix (p. 1171).
@val .................... Number from a string (p. 1175).
@wcount ............. Number of words in the string list (p. 1188).
@wcross .............. String with words in first list crossed with second (p. 1188).
@wdelim ............. Replace delimiters in string (p. 1189).
@wdrop ............... Drop words from string list (p. 1191).
@wexpand ........... String representation of automatic dummy variables (p. 1192).
@wfind................ Find location of word (case-sensitive) in string list (p. 1196).
@wfname ............ String containing name of current workfile (p. 1198).
@wfindnc ............ Find location of word (not case-sensitive) in string list (p. 1197).
@winterleave ....... Interleave words of two string lists (p. 1200).
@wintersect ......... Intersection of words in two string lists (p. 1201).
@wjoin ................ Extract elements of an Svector to a string (p. 1202).
@wkeep............... Keep subset of words in string list (p. 1202).
@wleft ................. Left-most words of string list (p. 1203).
@wmid ................ Middle or middle to end words of a string list (p. 1206).
@wnotin .............. Words not in a string list (p. 1207).
@word................. Single word from a string list (p. 1208).
@wordq ............... Single word from a string list, preserving quotes (p. 1209).
@wread ............... Read contents of text file into a string (p. 1210).
@wreplace ........... Replace characters in each word in a string list (p. 1211).
@wrfind............... Find location of a word (case-sensitive) in a string list searching
from end (p. 1212).
@wrfindnc ........... Find location of a word (not case-sensitive) in a string list searching
from end (p. 1213).
@wright............... Right-most words of a string list (p. 1214).
@wsort ................ Sorted list of words in a string list (p. 1215).
@wsplit ............... Create string vector from words in a string list (p. 1216).
@wunion ............. Union of words in two string lists (p. 1216).
@wunique ........... Remove duplicate words in string list (p. 1217).
Date Function Summary—333

Date Function Summary


Element Functions
@dateadd..............Date number after applying offset (p. 815).
@datediff ..............Difference between two date numbers (p. 817).
@dateceil..............Last possible date in a time period (p. 819).
@datefloor ............Earliest possible date in a time period (p. 820).
@datenext ............First possible date in the next time period (p. 821).
@datepart .............Extract part of a date number (p. 823).
@datestr ...............String representation of a date number (p. 824).
@dateval ..............Date number associated with a string representation of a date
(p. 825).
@localt .................Convert UTC (Coordinated Universal Time) to local time (p. 946).
@makedate...........Convert numeric representation of a date to date number (p. 960).
@now...................Current time date number (p. 1013).
@strnow...............String representation of the current date and time (p. 1132).
@time...................Current time as a string (p. 1146).
@tz ......................Convert time in source time zone to destination time (p. 1155).
@tzlist ..................Available time zone specifications (p. 1155).
@tzspec ................Time zone specification (p. 1156).
@utc.....................Convert local time to UTC (Coordinated Universal Time) (p. 1173).

Utility Functions
@dtoo...................Observation number in the workfile associated with a date string
(p. 847).
@otod...................Workfile observation to date string (p. 1019).
@otods .................Sample observation to date string (p. 1020).

Workfile Series Functions


@after ..................Indicators for whether observation postdates a date (p. 716).
@before ................Indicator for whether observation precedes a date (p. 721).
@date ...................Date number of observation (p. 814).
@day ....................Day of observation (p. 826).
@daycount ...........Number of days of week in observation (p. 827).
@during ...............Indicator of whether an observation is between two dates (p. 854).
@event .................Event identifier for observation (p. 878).
@enddate .............Last possible date of observation (p. 870).
@holiday ..............Holiday identifier for observation (p. 901).
@holidayset ..........Multiple holiday identifiers for observation (p. 905).
@hour ..................Hour of the day of the observation (integer) (p. 910).
334—Chapter 14.Date Function Summary

@hourf ................ Hour of the date of the observation (floating point) (p. 910)
@isperiod............. Is this the first observation matching the specified period (p. 930).
@minute .............. Minute of the hour of the observation (p. 978).
@month............... Month of the year of the observation (p. 983).
@quarter.............. Quarter of the year of the observation (p. 1059).
@seas .................. Seasonal dummy variable (p. 1109).
@second .............. Seconds of the minute of the observation (p. 1109).
@weekday ........... Day of the week of the observation (p. 1192).
@year .................. Year of the observation (p. 1223).
Chapter 15. Matrix Language Summary

The following entries constitute a listing of the commands and functions used with EViews
matrix objects. For a description of the EViews matrix language, see Chapter 11. “Matrix
Language,” on page 279.

Matrix Command Summary


colplace ................Places column vector into matrix (p. 410).
matplace ...............Places matrix object in another matrix object (p. 518).
mtos .....................Converts a matrix object to series or group (p. 522).
nrnd .....................Fill the matrix with normal random numbers (p. 523).
rmvnorm ..............Fill the matrix with multivariate normal random numbers (p. 574).
rnd .......................Fill the matrix with uniform random numbers (p. 575).
rndint ...................Fill the matrix with random integers numbers (p. 576).
rowplace ...............Places a rowvector in matrix object (p. 581).
stom .....................Converts series or group to vector or matrix after removing observa-
tions with NAs (p. 598).
stomna..................Converts series or group to vector or matrix without removing
observations with NAs (p. 599).
ttom......................Fills a matrix with the numeric contents of a table (p. 617).

Matrix Function Summary


Matrix Utility
@capplyranks .......Reorder the rows of the matrix using a vector of ranks (p. 733).
@columnextract....Extract column from matrix (p. 762).
@columns ............Number of columns in matrix object or group (p. 762).
@convert ..............Converts series or group to a vector or matrix after removing NAs
(p. 764).
@eqna ..................Test for equality of data objects, treating NAs and null strings as
ordinary and not missing values (p. 873).
@explode..............Square matrix from a sym matrix object (p. 880).
@fill .....................Vector initialized from a list of values (p. 884).
@filledmatrix ........Matrix initialized with scalar value (p. 884).
@filledrowvector...Rowvector initialized with scalar value (p. 885).
@filledsym ...........Sym initialized with scalar value (p. 885).
@filledvector ........Vector initialized with scalar value (p. 886).
336—Chapter 15.Matrix Function Summary

@getmaindiagonal Extract main diagonal from matrix (p. 895).


@grid................... Vector containing equally spaced grid of values (p. 897).
@hcat .................. Vertically concatenate matrices (p. 899).
@identity ............. Identity matrix (p. 913)
@implode ............ Creates sym from lower triangle of square matrix (p. 919).
@implodeu .......... Creates sym from upper triangle of square matrix (p. 920).
@isna .................. Test for missing values (p. 927).
@lower ................ Lowercase representation of a string, or lower triangular matrix of a
matrix (p. 951).
@makediagonal.... Create a matrix with vector placed on a diagonal (p. 961).
@mnrnd .............. Matrix of normal random numbers (p. 982).
@neqna ............... Inequality test (NAs and blanks treated as values, not missing val-
ues) (p. 1010).
@ones.................. Matrix or vector of ones (p. 1018).
@permute ............ Permutation of matrix (p. 1037).
@range ................ Vector of sequential integers (p. 1063).
@ranks ................ Ranking of values (p. 1064).
@rapplyranks....... Reorder the columns of a matrix using a vector of ranks (p. 1065).
@resample ........... Randomly draw from the rows of the matrix (p. 1071).
@rmvnorm .......... Multivariate normal random draws (p. 1085).
@rowextract......... Extract rowvector from matrix object (p. 1089).
@rows ................. Number of rows (p. 1090).
@rwish ................ Wishart random draw (p. 1104).
@subextract ......... Extract submatrix from matrix object (p. 1133).
@scale ................. Scale rows or columns of matrix (p. 1108).
@seq.................... Vector containing arithmetic sequence (p. 1110).
@seqm................. Vector containing geometric sequence (p. 1111).
@sfill ................... Create a string vector from a list of strings (p. 1111).
@sort ................... Sort elements of data object (p. 1116).
@unvec................ Unstack vector into a matrix (p. 1170).
@unvech.............. Unstack vector into lower triangle of sym (p. 1171).
@uniquevals ........ Vector or svector of unique values of object (p. 1169).
@unitvector ......... Extracts column from an identity matrix (p. 1169).
@upper ................ Uppercase representation of a string; or upper triangular matrix of a
matrix (p. 1171).
@vcat .................. Vertically concatenate matrices (p. 1182).
@vec.................... Vectorize (stack columns of) matrix (p. 1183).
@vech.................. Vectorize (stack columns of) lower triangle of matrix (p. 1184).
@zeros................. Matrix or vector of zeros (p. 1225).
Matrix Function Summary—337

Matrix Algebra
@cholesky ............Cholesky factor of matrix (p. 743).
@commute ...........Commutation matrix (p. 763).
@cond ..................Condition number of square matrix or sym (p. 763).
@det.....................Determinant of matrix (p. 835).
@duplic ................Duplication matrix (p. 849).
@duplicinv ...........Inverse duplication matrix (p. 850).
@eigenvalues........Vector of eigenvalues of a sym (p. 864).
@eigenvectors.......Matrix whose columns contain the eigenvectors of a matrix
(p. 864).
@elimin................Elimination matrix (p. 867).
@inner .................Inner product (p. 922).
@inverse ..............Inverse of matrix (p. 926).
@issingular...........Test matrix for singularity (p. 931).
@kronecker ..........Kronecker product (p. 935).
@lu ......................LU decomposition of a matrix (p. 954).
@norm .................Norm of series or matrix object (p. 1012).
@outer .................Outer product of vectors or series (p. 1021).
@pinverse.............Moore-Penrose pseudo-inverse of matrix (p. 1038).
@qform ................Quadratic form (p. 1049).
@qr ......................QR decomposition (p. 1055).
@rank ..................Rank of a matrix (p. 1063).
@rsweep...............Reverse sweep operator (p. 1097).
@solvesystem .......Solve system of linear equations (p. 1115).
@svd ....................Singular value decomposition (economy) of matrix (p. 1137).
@svdfull ...............Singular value decomposition (full) of matrix (p. 1139).
@sweep ................Sweep operator (p. 1140).
@trace ..................Computes the trace of a square matrix or sym (p. 1147).
@transpose ...........Transpose of a matrix object (p. 1147).
@unvec ................Unstack vector into a matrix (p. 1170).
@unvech ..............Unstack vector into lower triangle of sym (p. 1171).
@vec ....................Vectorize (stack columns of) matrix (p. 1183).
@vech ..................Vectorize (stack columns of) lower triangle of matrix (p. 1184).

Matrix Statistics
@columns ............Number of columns in matrix object or group (p. 762).
@cor.....................Correlation of two vectors or series, or between the columns of a
matrix or series in a group (p. 766).
338—Chapter 15.Matrix Function Summary

@cov ................... Covariance (non-d.f.corrected) of two vectors or series, or between


the columns of a matrix or series in a group (p. 767).
@covp ................. Covariance (non-d.f. corrected) of two vectors or series, or between
the columns of a matrix or series in a group (p. 767).
@covs .................. Covariance (d.f. corrected) of two vectors or series, or between the
columns of a matrix or series in a group (p. 769).
@first................... The first non-missing value in the vector or series (p. 886).
@gmean............... Geometric mean (p. 896).
@hmean .............. Harmonic mean (p. 900).
@ifirst.................. Index of the first non-missing value in the vector or series (p. 914).
@ilast .................. Index of the last non-missing value in the vector or series (p. 915).
@imax ................. Index of maximum value (p. 915).
@imaxes .............. Indices of maximum value (multiple) (p. 917).
@imin.................. Index of minimum value (p. 918).
@imins ................ Indices of minimum value (multiple) (p. 918).
@inner................. Inner product (p. 922).
@intercept ........... Intercept from a trend regression (p. 925).
@kurt .................. Kurtosis (p. 936).
@last ................... The last non-missing value in the vector or series (p. 940).
@mae .................. Mean of absolute error (difference) between series (p. 959).
@mape ................ Mean absolute percentage error (difference) between series
(p. 963).
@max .................. Maximum value (p. 965).
@maxes ............... Maximum values (multiple) (p. 966).
@mean ................ Arithmetic mean (p. 971).
@median ............. Median (p. 973).
@min................... Minimum value (p. 975).
@mins ................. Minimum values (multiple) (p. 976).
@mse................... Mean of square error (difference) between series (p. 1000).
@nas ................... Number of missing observations (p. 1009).
@norm ................ Norm of series or matrix object (p. 1012).
@obs ................... Number of observations (p. 1015).
@prod.................. Product (p. 1042).
@quantile ............ Empirical quantile (p. 1057).
@regress .............. Perform an OLS regression on the first column of a matrix versus
the remaining columns (p. 1069).
@rmse ................. Root of the mean of square error (difference) between series
(p. 1084).
@rows ................. Number of rows (p. 1090).
Matrix Function Summary—339

@skew .................Skewness (p. 1113).


@smape................Symmetric mean absolute percentage error (difference) between
series (p. 1114).
@stdev .................Sample standard deviation (d.f. adjusted) (p. 1117).
@stdevp................Population standard deviation (no d.f. adjustment) (p. 1118).
@stdevs ................Sample standard deviation (d.f. adjusted) (p. 1119).
@stdize ................Standardized data (using sample standard deviation) (p. 1121).
@stdizep...............Standardized data (using population standard deviation) (p. 1122).
@sum...................Arithmetic sum (p. 1140).
@sumsq................Arithmetic sum of squares (p. 1136).
@theil...................Theil inequality coefficient (difference) between series (p. 1145).
@trendcoef ...........Trend coefficient from detrending regression (p. 1151).
@trmean...............Trimmed mean (p. 1154).
@uniquevals.........Vector or svector of unique values of object (p. 1169).
@var ....................Population variance (no d.f. adjustment) (p. 1179).
@varp...................Population variance (no d.f. adjustment) (p. 1179).
@vars ...................Sample variance (d.f. adjusted) (p. 1181).

Matrix Column Statistics


@cfirst..................First non-missing value in each column of a matrix (p. 740).
@cifirst.................Index of the first non-missing value in each column of a matrix
(p. 744).
@cilast .................Index of the last non-missing value in each column of a matrix
(p. 745).
@cimax ................Index of the maximal value in each column of a matrix (p. 746).
@cimin.................Index of the maximal value in each column of a matrix (p. 746).
@cintercept...........Intercept from a trend regression performed on each column of a
matrix (p. 747).
@clast ..................Last non-missing value in each column of the matrix (p. 748).
@cmax .................Maximal value in each column of a matrix (p. 750).
@cmean ...............Mean in each column of a matrix (p. 751).
@cmedian.............Median of each column of a matrix (p. 751).
@cmin..................Minimal value for each column of the matrix (p. 752).
@cnas...................Number of NA values in each column of a matrix (p. 752).
@cobs...................Number of non-NA values in each column of a matrix (p. 754).
@cprod.................Product of elements in each column of a matrix (p. 771).
@cquantile ...........Quantile of each column of a matrix (p. 771).
@cstdev ................Sample standard deviation (d.f. corrected) of each column of a
matrix (p. 772).
340—Chapter 15.Matrix Function Summary

@cstdevp ............. Population standard deviation (non-d.f. corrected) of each column


of a matrix (p. 773).
@cstdevs.............. Sample standard deviation (non-d.f. corrected) of each column of a
matrix (p. 773).
@csum................. Sum of the values in each column of a matrix (p. 774).
@csumsq ............. Sum of the squared values in each column of a matrix (p. 774).
@ctrendcoef ......... Slope from a trend regression on each column of a matrix (p. 775).
@ctrmean ............ Trimmed mean of each column of a matrix (p. 776).
@cvar .................. Population variance of each column of a matrix (p. 807).
@cvarp ................ Population variance of each column of a matrix (p. 807).
@cvars................. Sample variance of each column of a matrix (p. 808).

Matrix Element
@ediv .................. Element by element division of two matrices (p. 861).
@eeq ................... Element by element equality comparison of two data objects
(p. 861).
@eeqna................ Element by element equality comparison of two data objects with
NAs treated as ordinary value for comparison (p. 862).
@ege.................... Element by element tests for whether the elements in the data
objects are greater than or equal to corresponding elements in
another data object (p. 863).
@egt .................... Element by element tests for whether the elements in the data
object strictly greater than corresponding elements in another data
object (p. 863).
@einv .................. Element by element inverses of a matrix (p. 865).
@ele .................... Element by element tests for whether the elements in the data
object are less than or equal to corresponding elements in another
data object (p. 866).
@elt ..................... Element by element tests for whether the elements in the data
object are strictly less than corresponding elements in another data
object (p. 867).
@emax ................ Element by element maximums of two conformable data objects
(p. 868).
@emin ................. Element by element minimums of two conformable data objects
(p. 868).
@emult ................ Element by element multiplication of two matrix objects (p. 869).
@eneq ................. Element by element inequality comparison of two data objects
(p. 870).
@eneqna.............. Element by element inequality comparison of two data objects with
NAs treated as ordinary value for comparison (p. 871).
Matrix Function Summary—341

@epow .................Raises each element in a matrix to a power (p. 873).


@erecode..............Element by element recode of data objects (p. 876).

Matrix Transformation
Overall Transformations
@capplyranks .......Reorder the rows of the matrix using a vector of ranks (p. 733).
@demean .............Compute deviations from the mean of the data object (p. 834).
@detrend ..............Compute deviations from the trend of the data object (p. 836).
@dupselem...........Identifier for the observation within the set of duplicates (p. 851).
@dupsid ...............Identifier for the duplicates group for the observation (p. 852).
@dupsobs .............Number of observations in the corresponding duplicates group
(p. 853).
@permute.............Permutation of matrix (p. 1037).
@ranks .................Ranking of values (p. 1064).
@rapplyranks .......Reorder the columns of a matrix using a vector of ranks (p. 1065).
@resample............Randomly draw from the rows of the matrix (p. 1071).
@transpose ...........Transpose of a matrix object (p. 1147).
By-Column Transformations
@colcumprod .......Cumulative products for each column of a matrix (p. 754).
@colcumsum ........Cumulative sums for each column of a matrix (p. 755).
@coldemean .........Demean each column of a matrix (p. 756).
@coldetrend .........Detrend each column of a matrix (p. 757).
@colpctiles ...........Percentile values for each column of a matrix (p. 758).
@colranks ............Ranks of each column of the matrix (p. 758).
@colsort ...............Sort each column of the matrix (p. 759).
@colstdize ............Standardize each column using the sample (d.f. corrected) standard
deviation (p. 760).
@colstdizep ..........Standardize each column using the population (non-d.f. corrected)
standard deviation (p. 761).
By-Row Transformations
@rowranks ...........Matrix where each row contains ranks of the column values
(p. 1090).
@rowsort..............Matrix where each row contains sorted columns (p. 1091).
342—Chapter 15.Matrix Function Summary
Chapter 16. Programming Language Summary

The following reference is a summary of the program statements, commands, and functions
commonly used by the EViews programming language.

The summary section contains links to documentation entries for the various types of infor-
mation. The remainder provides the actual entries for the program statements.

For details on the EViews programming language, see Chapter 6. “EViews Programming,” on
page 129.

Program Statements
call .......................calls a subroutine within a program (p. 347).
else .......................denotes start of alternative clause for IF (p. 347).
endif .....................marks end of conditional commands (p. 348).
endsub..................marks end of subroutine definition (p. 348).
exitloop.................exits from current loop (p. 348).
for ........................start of FOR execution loop (p. 349).
if...........................conditional execution statement (p. 349).
include..................include subroutine in programs (p. 349).
next ......................end of FOR loop (p. 350).
return ...................exit subroutine (p. 351).
sleep .....................pause program (p. 351).
step.......................(optional) step size of a FOR loop (p. 352).
stop ......................halts execution of program (p. 353).
subroutine ............declares subroutine (p. 353).
then ......................part of IF statement (p. 353).
to..........................upper limit of FOR loop (p. 354).
wend ....................end of WHILE loop (p. 354).
while ....................start of WHILE loop (p. 355).

Support Commands
addin ....................register a program file as an EViews Add-in (p. 365).
adduo ...................register a user object (p. 367).
clearerrs................sets the current program error count to 0 (p. 393).
commandcap.........send text to the command capture window (p. 410).
deleteaddin ...........unregister a program file as an EViews Add-in (p. 443).
344—Chapter 16.Support Commands

exec ..................... execute a program (p. 444).


logclear ................ clears the log window of a program (p. 504).
logclose ................ closes one or more or all message log windows (p. 505).
logeval ................. sends result of the command to a log window (p. 506).
logmode ............... sets logging of specified messages (p. 506).
logmsg ................. adds a line of text to the program log (p. 509).
logsave................. saves the program log to a text file (p. 509).
open..................... opens a program file from disk (p. 524).
optimize............... find the solution to a user-defined optimization problem (p. 525).
output .................. redirects print output to objects or files (p. 533).
poff ...................... turns off automatic printing in programs (p. 350).
pon ...................... turns on automatic printing in programs (p. 351).
program ............... declares a program (p. 567).
run....................... runs a program (p. 581).
saveprgini ............ saves program variables in“.ini” file (p. 583).
seterr.................... sets a user-specified execution error (p. 587).
seterrcount ........... sets the current program execution error count (p. 587).
setmaxerrs............ sets the maximum number of errors that a program may encounter
before execution is halted (p. 588).
spawn .................. spawn a new process (p. 596).
statusline.............. sends message to the status line (p. 598).
tic ........................ reset the timer (p. 611).
toc ....................... display elapsed time (since timer reset) in seconds (p. 611).
xclose................... close an open connection to an external application (p. 668).
xget...................... retrieve data from an external application into an EViews object
(p. 668).
xlog...................... switch on or off the external application log inside EViews (p. 671).
xoff ...................... turns off mode that sends all subsequent command lines to the
external program (p. 671).
xon ...................... turns on mode that sends all subsequent command lines to the
external program (p. 672).
xopen................... open a connection to an external application (p. 672).
xpackage .............. installs the specified R package in the current external R connection
(p. 674).
xput ..................... send an EViews object to an external application (p. 675).
xrun..................... run a command in an external application (p. 677).
Support Functions—345

Support Functions
@addinspath.........EViews add-ins directory path @addinspath (p. 714).
@attrnames ..........Attribute names in workfile page (p. 718).
@attrvals ..............Attribute values in workfile page (p. 719).
@dbname .............String containing the default database name (p. 829).
@equaloption .......Equals-to option value provided in the exec or run commands
(p. 875).
@env....................Windows environment variable string (p. 872).
@errorcount .........Number of errors encountered running a program (p. 878).
@evpath ...............Directory path of the EViews executable (p. 877).
@fileexist..............Check for existence of a file on disk (p. 883).
@folderexist..........Check for existence of a folder on disk (p. 888).
@getnextname ......String containing next available name in the workfile (p. 895).
@getthistype .........Object type of active object (_this) (p. 896).
@hasoption...........Indicator for whether option is provided in the exec or run com-
mand (p. 899).
@isobject ..............Does object exist in active workfile page (p. 929).
@isvalidgroup.......Does the string represent a valid EViews group or auto-series
(p. 931).
@isvalidname .......Indicator for whether string represents a valid name for an EViews
object (p. 932).
@lasterrnum .........Last error number generated by a previously issued command
(p. 941).
@lasterrstr ............Last error message generated by a previously issued command
(p. 942).
@linepath .............Location of the program file currently being executed (p. 944).
@loadprgini ..........Variable name value in an “.ini” file (p. 945).
@makevalidname .Make string into a valid EViews name (p. 962).
@maxerrcount ......Maximum number of errors in a program before halting execution
(p. 966).
@option................Option string provided in the exec or run command (p. 1019).
@runpath .............Location of the program currently being executed (p. 1101).
@tablenames ........Tables names in a foreign file (p. 1143).
@temppath ...........Directory path for EViews temporary files (p. 1145).
@toc.....................Elapsed time (since timer reset) in seconds (p. 1146).
@vernum..............EViews version number (p. 1184).
@verstr.................EViews product name string (p. 1184).
@wdir ..................List of all files in a directory (p. 1190).
346—Chapter 16.Workfile Utility Functions

@wfattrnames ...... String containing a list of attribute names in the workfile (p. 1194).
@wfattrvals.......... String containing a list of attribute values in the workfile (p. 1195).
@wfpath .............. String containing path of current workfile (p. 1198).
@wlookup ........... String list formed from objects in a workfile or database matching a
pattern (p. 1204).
@wquery ............. String containing list of object attributes for objects matching a
database query (p. 1209).
@xgetstr .............. String value from the external application.(p. 1219).
@xgetnum ........... Scalar numeric value from the external application.(p. 1219).
@xputnames ........ List of objects created in foreign application using XPUT (p. 1220).
@xtype ................ Type of active external connection (p. 1220).
@xverstr .............. External application version number as a string (p. 1221).
@xvernum ........... External application version number as a number (p. 1221).

Workfile Utility Functions


@dtoo .................. Observation number in the workfile associated with a date string
(p. 847).
@ispanel .............. Is the current workfile page panel structured (p. 929).
@obsrange ........... Number of observations in the workfile page (p. 1017).
@obssmpl ............ Number of observations in the workfile sample (p. 1017).
@otod .................. Workfile observation to date string (p. 1019).
@otods................. Sample observation to date string (p. 1020).
@pagecount ......... Number of pages in workfile (p. 1024).
@pageexist........... Does a page exist in the workfile (p. 1024).
@pagefreq............ Frequency specification for the workfile page (p. 1025).
@pageids ............. Workfile page observation identifiers (p. 1026).
@pageidx ............. Index vector of the specified observations (p. 1027).
@pagelist ............. List of pages in workfile (p. 1028).
@pagename ......... Name of active workfile page (p. 1028).
@pagerange ......... Range specification of active workfile page (p. 1029).
@pagesmpl .......... Sample specification in active workfile page (p. 1030).
@pagesmplidx...... Index vector of observations in the current sample (p. 1030).

Dialog Display Functions


@uidialog ............ Display a dialog with multiple controls (p. 1159).
@uiedit ................ Display a dialog with an edit control (p. 1162).
@uifiledlg ............ Display a file open and save dialog (p. 1163).
@uilist ................. Display a dialog with a listbox control (p. 1164).
else—347

@uimlist...............Display a dialog with a multiple-select listbox control (p. 1165).


@uiprompt ...........Display a prompt dialog (p. 1166).
@uiradio...............Display a dialog with radio buttons (p. 1168).

Programming Language Entries


The following section provides an alphabetical listing of the commands and functions asso-
ciated with the EViews programming language. Each entry outlines the basic syntax and
provides examples and cross references.

call Program Statements

Call a subroutine within a program.

The call statement is used to call a subroutine within a program.

Cross-references
See “Calling Subroutines” on page 171. See also subroutine (p. 353), endsub (p. 348).

else Program Statements

ELSE clause of IF statement in a program.

Starts a sequence of commands to be executed when the IF condition is false. The else key-
word must be terminated with an endif.

Syntax
if [condition] then
[commands to be executed if condition is true]
else
[commands to be executed if condition is false]
endif

Cross-references
See “IF Statements” on page 157. See also, if (p. 349), endif (p. 348), then (p. 353).
348—Chapter 16.Dialog Display Functions

endif Program Statements

End of IF statement. Marks the end of an IF, or an IF-ELSE statement.

Syntax
if [condition] then
[commands if condition true]
endif

Cross-references
See “IF Statements” on page 157. See also, if (p. 349), else (p. 347), then (p. 353).

endsub Program Statements

Mark the end of a subroutine.

Syntax
subroutine name(arguments)
commands
endsub

Cross-references
See “Defining Subroutines,” beginning on page 168. See also, subroutine (p. 353),
return (p. 351).

exitloop Program Statements

Exit from current loop in programs.

exitloop causes the program to break out of the current FOR or WHILE loop.

Syntax
Command: exitloop

Examples
for !i=1 to 107
if !i>6 then exitloop
next
include—349

Cross-references
See “The FOR Loop” on page 160. See also, stop (p. 353), return (p. 351), for (p. 349),
next (p. 350), step (p. 352).

for Program Statements

FOR loop in a program.

The for statement is the beginning of a FOR...NEXT loop in a program.

Syntax
for counter=start to end [step stepsize]
[commands]
next

Cross-references
See “The FOR Loop” on page 160. See also, exitloop (p. 348), next (p. 350), step
(p. 352).

if Program Statements

IF statement in a program.

The if statement marks the beginning of a condition and commands to be executed if the
statement is true. The statement must be terminated with the beginning of an ELSE clause,
or an endif.

Syntax
if [condition] then
[commands if condition true]
endif

Cross-references
See “IF Statements” on page 157. See also else (p. 347), endif (p. 348), then (p. 353).

include Program Statements

Include another file in a program.

The include statement is used to include the contents of another file in a program file.
350—Chapter 16.Dialog Display Functions

If an include file is specified without an absolute path, the base location will be taken from
the location of the program file, not from the default directory.

Syntax
include filename

Cross-references
See “Multiple Program Files” on page 167. See also call (p. 347).

next Program Statements

End of FOR loop. next marks the end of a FOR loop in a program.

Syntax
for [conditions of the FOR loop]
[commands]
next

Cross-references
See “The FOR Loop,” beginning on page 160. See also, exitloop (p. 348), for (p. 349),
step (p. 352).

poff Program Statements

Turn off automatic printing in programs.

poff turns off automatic printing of all output. In programs, poff is used in conjunction
with pon to control automatic printing; these commands have no effect in interactive use.

Syntax
Command: poff

Cross-references
See “Print Setup” on page 2562 of the User’s Guide I for a discussion of printer control.

See also pon (p. 351).


sleep—351

pon Program Statements

Turn on automatic printing in programs.

pon instructs EViews to send all statistical and data display output to the printer (or the redi-
rected printer destination; see output (p. 533)). It is equivalent to including the “p” option
in all commands that generate output. pon and poff only work in programs; they have no
effect in interactive use.

Syntax
Command: pon

Cross-references
See “Print Setup” on page 2562 of the User’s Guide I for a discussion of printer control.

See also poff (p. 350).

return Program Statements

Exit subroutine.

The return statement forces an exit from a subroutine within a program. A common use of
return is to exit from the subroutine if an unanticipated error has occurred.

Syntax
if [condition] then
return
endif

Cross-references
See “Subroutines,” beginning on page 168. See also exitloop (p. 348), stop (p. 353).

sleep Program Statements

Pause program execution.

Syntax
sleep n

pauses a program by n milliseconds (default is 5000).


352—Chapter 16.Dialog Display Functions

Example
sleep 1000

step Program Statements

Step size of a FOR loop.

Syntax
for !i=a to b step n
[commands]
next

step may be used in a FOR loop to specify the size of the step in the looping variable. If no
step is provided, for assumes a step of “+1”.

If a given step exceeds the end value b in the FOR loop specification, the contents of the
loop will not be executed.

Examples
for !j=5 to 1 step -1
series x = nrnd*!j
next

repeatedly executes the commands in the loop with the control variable !J set to “5”, “4”,
“3”, “2”, “1”.
for !j=0 to 10 step 3
series z = z/!j
next

Loops the commands with the control variable !J set to “0”, “3”, “6”, and “9”.

You should take care when using non-integer values for the stepsize since round-off error
may yield unanticipated results. For example:
for !j=0 to 1 step .01
series w = !j
next

may stop before executing the loop for the value !J=1 due to round-off error.

Cross-references
See “The FOR Loop,” beginning on page 160. See also exitloop (p. 348), for (p. 349),
next (p. 350).
then—353

stop Program Statements

Break out of program.

The stop command halts execution of a program. It has the same effect as hitting the F1
(break) key.

Syntax
Command: stop

Cross-references
See also, exitloop (p. 348), return (p. 351).

subroutine Program Statements

Declare a subroutine within a program.

The subroutine statement marks the start of a subroutine.

Syntax
subroutine name(arguments)
[commands]
endsub

Cross-references
See “Subroutines,” beginning on page 168. See also endsub (p. 348).

then Program Statements

Part of IF statement.

then marks the beginning of commands to be executed if the condition given in the IF state-
ment is satisfied.

Syntax
if [condition] then
[commands if condition true]
endif
354—Chapter 16.Dialog Display Functions

Cross-references
See “IF Statements” on page 157. See also, else (p. 347), endif (p. 348), if (p. 349).

to Expression || Program Statements

Upper limit of for loop OR lag range specifier.

to is required in the specification of a FOR loop to specify the upper limit of the control vari-
able; see “The FOR Loop” on page 160.

When used as a lag specifier, to may be used to specify a range of lags to be used in estima-
tion.

Syntax
Used in a FOR loop:
for !i=n to m
[commands]
next
Used as a Lag specifier:
series_name(n to m)

Examples
ls cs c gdp(0 to -12)

Runs an OLS regression of CS on a constant, and the variables GDP, GDP(–1), GDP(–2), …,
GDP(–11), GDP(–12).

Cross-references
See “The FOR Loop,” beginning on page 160. See also, exitloop (p. 348), for (p. 349),
next (p. 350).

wend Program Statements

End of WHILE clause.

wend marks the end of a set of program commands that are executed under the control of a
WHILE statement.

Syntax
while [condition]
[commands while condition true]
while—355

wend

Cross-references
See “The WHILE Loop” on page 164. See also while (p. 355).

while Program Statements

Conditional control statement. The while statement marks the beginning of a WHILE loop.

The commands between the while keyword and the wend keyword will be executed repeat-
edly until the condition in the while statement is false.

Syntax
while [condition]
[commands while condition true]
wend

Cross-references
See “The WHILE Loop” on page 164. See also wend (p. 354).
356—Chapter 16.Dialog Display Functions
Chapter 17. Command Reference

Commands
The following list summarizes the EViews basic commands.

Other chapters document different aspects of the command language:


• Special EViews expressions are described in Chapter 13. “Special Expression Refer-
ence,” beginning on page 323.
• EViews functions are documented in Chapter 18. “Function Reference,” on page 679
• Views and procedures for each EViews object may be found in Chapter 1. “Object
View and Procedure Reference,” on page 3 of the Object Reference.

Command Actions
do .........................execute action without opening window (p. 435).
freeze....................create view object (p. 457).
preview.................preview objects contained in a database or workfile (p. 564).
print .....................print view (p. 566).
show.....................show object window (p. 589).

Global Commands
cd .........................change default directory (p. 388).
exit .......................exit the EViews program (p. 446).
help ......................displays the documentation (p. 476).
output...................redirect printer output (p. 533).
param ...................set parameter values (p. 564).
rndseed .................set the seed of the random number generator (p. 577).
smpl .....................set the sample range (p. 592).

Object Creation Commands


alpha ....................alpha series (p. 8).
coef.......................coefficient vector (p. 26).
data ......................enter data from keyboard (p. 423).
equation................equation object (p. 133).
factor ....................factor analysis object (p. 282).
frml ......................numeric or alpha series object with a formula for auto-updating
(p. 458).
genr ......................numeric or alpha series object (p. 462).
358—Chapter 17.Command Reference

graph ................... graph object—create using a graph command or by merging exist-


ing graphs (p. 401).
group ................... group object (p. 478).
link ...................... series or alpha link object (p. 530).
logl ...................... likelihood object (p. 547).
matrix .................. matrix object (p. 585).
model................... model object (p. 631).
pool ..................... pool object (p. 677).
rowvector ............. rowvector object (p. 729).
sample ................. sample object (p. 743).
scalar ................... scalar object (p. 751).
series ................... numeric data object (p. 832).
spool .................... spool object (p. 926).
sspace .................. sspace object (p. 954).
string ................... string object (p. 967).
svector ................. svector object (p. 988).
sym...................... sym object (p. 1027).
system.................. system object (p. 1066).
table..................... table object (p. 1110).
text ...................... text object (p. 1120).
userobj ................. user object (p. 1131).
valmap ................. valmap object (p. 1140).
var ....................... var estimation object (p. 1214).
vector................... vector object (p. 1263).

Object Container, Data, and File Commands


ccopy ................... copy series from DRI database (p. 388).
cfetch ................... fetch series from DRI database (p. 391).
clabel ................... display DRI series description (p. 393).
close .................... close object, program, or workfile (p. 393).
copy ..................... copy objects within and between workfiles, workfile pages, and
databases (p. 411).
db ........................ open or create a database (p. 424).
dbcopy ................. make copy of a database (p. 424).
dbcreate ............... create a new database (p. 426).
dbdelete ............... delete a database (p. 428).
dbopen ................. open a database (p. 428).
dbpack ................. pack a database (p. 431).
dbrebuild ............. rebuild a database (p. 431).
Commands—359

dbrename..............rename a database (p. 432).


delete....................delete objects from a workfile (p. 432).
driconvert .............convert the entire DRI database to an EViews database (p. 436).
expand..................expand workfile range (p. 446).
fetch .....................fetch objects from databases or databank files (p. 449).
hconvert ...............convert an entire Haver Analytics database to an EViews database
(p. 476).
hfetch ...................fetch series from a Haver Analytics database (p. 477).
hlabel ...................obtain label from a Haver Analytics database (p. 478).
import...................imports data from a foreign file or a previously saved workfile into
the current default workfile (p. 480).
importattr .............imports observation values stored inside one or more series in a
second workfile page into the attribute fields of objects within the
current workfile page (p. 487).
importmat .............imports data from a foreign file into a matrix object in the current
workfile (p. 489).
importtbl...............imports data from a foreign file into a table object in the current
workfile (p. 496).
load ......................load a workfile (p. 504).
open .....................open a program or text (ASCII) file (p. 524).
optsave .................save the current EViews global options settings .INI files into a
directory (p. 530).
optset....................replace the current EViews global options settings .INI files with
ones based in a different directory (p. 531).
pageappend...........append observations to workfile page (p. 536).
pagecontract..........contract workfile page (p. 537).
pagecopy...............copy contents of a workfile page (p. 538).
pagecreate.............create a workfile page (p. 540).
pagedelete .............delete a workfile page (p. 546).
pageload ...............load one or more pages into a workfile from a workfile or a foreign
data source (p. 546).
pagerefresh ...........refresh all links and auto-series in the active workfile page—primar-
ily used to refresh links that use external database data (p. 547).
pagerename ..........rename a workfile page (p. 548).
pagesave ...............save page into a workfile or a foreign data source (p. 548).
pageselect .............make specified page active (p. 554).
pagesort ................sort the workfile (p. 595).
pagestack ..............reshape the workfile page by stacking observations (p. 555).
pagestruct .............apply a workfile structure to the page (p. 558).
360—Chapter 17.Command Reference

pageunlink ........... break links in all link objects and auto-updating series (formulae) in
the active workfile page (p. 561).
pageunstack ......... reshape the workfile page by unstacking observations into multiple
series (p. 562).
range.................... reset the workfile range (p. 570).
read ..................... import data from a foreign disk file into series (p. 570).
save ..................... save workfile to disk (p. 583).
sort ...................... sort the workfile(p. 595).
store..................... store objects in database and databank files (p. 600).
unlink .................. break links and auto-updating series (formulae) in the specified
series objects (p. 618).
wfclose................. close the active workfile (p. 631).
wfcompare ........... compare the contents of the current workfile or page with the con-
tents of a different workfile, page, or database (p. 634).
wfcreate ............... create a new workfile (p. 634).
wfdetails .............. change the details displayed in the current workfile window
(p. 638).
wfdir .................... change the workfile view to a simple object directory listing
(p. 639).
wffilter ................. change the workfile object filter for the current workfile window
(p. 639).
wfopen................. open workfile or foreign source data as a workfile (p. 640).
wforder ................ change the workfile page order (p. 655).
wfrefresh.............. refresh all links and auto-series in the active workfile—primarily
used to refresh links that use external database data (p. 656).
wfsave.................. save workfile to disk as a workfile or a foreign data source (p. 656).
wfselect................ change active workfile page (p. 663).
wfsnapshot........... takes a manual snapshot of the current workfile (p. 663).
wfstats ................. display the workfile statistics and summary view (p. 664).
wfunlink .............. break links in all link objects and auto-updating series (formulae) in
the active workfile (p. 664).
wfuse ................... activate a workfile (p. 665).
workfile ............... create or change active workfile (p. 666).
write .................... write series to a disk file (p. 666).

Object Utility Commands


close .................... close window of an object, program, or workfile (p. 393).
copy ..................... copy objects (p. 411).
delete ................... delete objects (p. 432).
rename................. rename object (p. 573).
Commands—361

Object Assignment Commands


data ......................enter data from keyboard (p. 423).
frml ......................assign formula for auto-updating to a numeric or alpha series object
(p. 458).
genr ......................create numeric or alpha series object (p. 462).
nrnd .....................fill object with standard normal random numbers (p. 523).
rmvnorm ..............fill object with multivariate normal random numbers (p. 574).
rnd .......................fill object with uniform random numbers (p. 575).
rndint ...................fill object with random integers (p. 576).
rndseed .................set random number generator seed (p. 577).

Matrix Utility Commands


colplace ................Places column vector into matrix (p. 410).
matplace ...............Places matrix object in another matrix object (p. 518).
mtos .....................Converts a matrix object to series, alpha, or group (p. 522).
nrnd .....................Fill the matrix with normal random numbers (p. 523).
rmvnorm ..............Fill the matrix with multivariate normal random numbers (p. 574).
rnd .......................Fill the matrix with uniform random numbers (p. 575).
rowplace ...............Places a rowvector in matrix object (p. 581).
stom .....................Converts series, alpha, or group to vector or matrix after removing
observations with NAs (p. 598).
stomna..................Converts series, alpha or group to vector or matrix without remov-
ing observations with NAs (p. 599).
ttom......................Fills a matrix with the numeric contents of a table (p. 617).

Graph Creation Commands


Graph creation is discussed in detail in “Graph Creation Command Summary” on page 1266
of the Object Reference. All of the page numbers in this section refer to the Object Reference.
area ......................area graph (p. 1268).
band .....................area band graph (p. 1271).
bar........................bar graph (p. 1274).
boxplot .................boxplot graph (p. 1278).
distplot .................distribution graph (p. 1282).
dot ........................dot plot graph (p. 1289).
errbar ...................error bar graph (p. 1293).
hilo.......................high-low(-open-close) graph (p. 1295).
line .......................line-symbol graph (p. 1297).
mixed ...................mixed type graph (p. 1300).
pie ........................pie chart (p. 1303).
362—Chapter 17.Command Reference

qqplot .................. quantile-quantile graph (p. 1305).


scat ...................... scatterplot (p. 1309).
scatmat ................ matrix of all pairwise scatterplots (p. 1314).
scatpair ................ scatterplot pairs graph (p. 1317).
seasplot ................ seasonal line graph (p. 1321).
spike .................... spike graph (p. 1322).
xyarea .................. XY area graph (p. 1326).
xybar ................... XY bar graph (p. 1329).
xyline................... XY line graph (p. 1332).
xypair .................. XY pairs graph (p. 1336).

Table Commands
setcell................... format and fill in a table cell (p. 585).
setcolwidth........... set width of a table column (p. 586).
setline .................. place a horizontal line in table (p. 588).
tabplace................ insert a table into another table (p. 605).
ttom ..................... fills a matrix with the numeric contents of a table (p. 617).

Note that with the exception of tabplace, these commands are supported primarily for
backward compatibility. There is a more extensive set of table procs for working with and
customizing tables. See “Table Procs,” on page 1072 of the Object Reference.

Programming Commands
addin ................... register an Add-in (p. 365).
adduo................... register a user object (p. 367).
clearerrs ............... sets the current program error count to 0 (p. 393).
commandcap ........ send text to the command capture window (p. 410).
deleteaddin........... unregister a program file as an EViews Add-in (p. 443).
exec ..................... execute a program (p. 444).
logclear ................ clears the log window of a program (p. 504).
logclose ................ closes one or more or all message log windows (p. 505).
logeval ................. sends result of the command to a log window (p. 506).
logmode ............... sets logging of specified messages (p. 506).
logmsg ................. adds a line of text to the program log (p. 509).
logsave................. saves the program log to a text file (p. 509).
open..................... open a program file (p. 524).
optimize............... find the solution to a user-defined optimization problem (p. 525).
output .................. redirects print output to objects or files (p. 533).
poff ...................... turns off automatic printing in programs (p. 350).
pon ...................... turns on automatic printing in programs (p. 351).
Commands—363

program ................create a new program (p. 567).


run .......................run a program (p. 581).
saveprgini .............saves program variables in“.ini” file (p. 583).
seterr ....................sets a user-specified execution error (p. 587).
seterrcount............sets the current program execution error count (p. 587).
setmaxerrs ............sets the maximum number of errors that a program may encounter
before execution is halted (p. 588).
spawn ...................spawn a new process (p. 596).
statusline ..............send message to the status line (p. 598).
tic .........................reset the timer (p. 611).
toc ........................display elapsed time (since timer reset) in seconds (p. 611).

External Interface Commands


xclose ...................close an open connection to an external application (p. 668).
xget ......................retrieve data from an external application into an EViews object
(p. 668).
xlog ......................switch on or off the external application log inside EViews (p. 671).
xoff.......................turns off mode that sends all subsequent command lines to the
external program (p. 671).
xon .......................turns on mode that sends all subsequent command lines to the
external program (p. 672).
xopen ...................open a connection to an external application (p. 672).
xpackage...............installs the specified R package in the current external R connection
(p. 672).
xput ......................send an EViews object to an external application (p. 675).
xrun .....................run a command in an external application (p. 677).

Interactive Use Commands


The following commands have object command forms (e.g., Equation::arch). These
commands are particularly suited for interactive command line use. In general, we recom-
mend that you use the object forms of the commands.
arch ......................estimate autoregressive conditional heteroskedasticity (ARCH and
GARCH) models (p. 368).
archtest .................LM test for the presence of ARCH in the residuals (p. 374).
ardl.......................autoregressive distributed lag models (p. 375).
auto ......................Breusch-Godfrey serial correlation Lagrange Multiplier (LM) test
(p. 381).
binary ...................binary dependent variable models (includes probit, logit, gompit)
models (p. 382).
364—Chapter 17.Command Reference

breakls ................. least squares with breakpoints and breakpoint determination


(p. 467).
cause.................... pairwise Granger causality tests (p. 387).
censored............... estimate censored and truncated regression (includes tobit) models
(p. 389).
chow.................... Chow breakpoint and forecast tests for structural change (p. 392).
coint .................... cointegration test (p. 395).
cointreg................ estimate cointegrating equation using FMOLS, CCR, or DOLS
(p. 402).
cor ....................... correlation matrix (p. 418).
count ................... count data modeling (includes poisson, negative binomial and
quasi-maximum likelihood count models) (p. 419).
cov....................... covariance matrix (p. 421).
cross .................... cross correlogram (p. 422).
data...................... enter data from keyboard (p. 423).
did ....................... estimate a panel equation using the difference-in-difference estima-
tor (p. 434).
enet...................... elastic net regression (including Lasso and ridge regression)
(p. 436).
facbreak ............... factor breakpoint test for stability (p. 446).
factest .................. estimate a factor analysis model (p. 447).
fit......................... static forecast from an equation (p. 452).
forecast ................ dynamic forecast from an equation (p. 455).
funcoef................. estimate a functional coefficient regression equation (p. 460).
glm ...................... estimate a Generalized Linear Model (GLM) (p. 463).
gmm .................... estimate an equation using generalized method of moments
(p. 467).
heckit................... estimate a selection equation using the Heckman ML or 2-step
method (p. 474).
hist ...................... histogram and descriptive statistics (p. 477).
hpf ....................... Hodrick-Prescott filter (p. 479).
liml ...................... estimate an equation using Limited Information Maximum Likeli-
hood and K-class Estimation (p. 503).
logit ..................... logit (binary) estimation (p. 506).
ls ......................... equation using least squares or nonlinear least squares (p. 510).
midas ................... estimate an equation using Mixed Data Sampling (MIDAS) regres-
sion (p. 519).
ordered ................ ordinal dependent variable models (includes ordered probit,
ordered logit, and ordered extreme value models) (p. 532).
addin—365

probit....................probit (binary) estimation (p. 567).


qreg ......................estimate an equation using quantile regression (p. 567).
reset......................Ramsey’s RESET test for functional form (p. 574).
robustls.................robust regression (M-estimation, S-estimation and MM-estimation)
(p. 578).
seas ......................seasonal adjustment for quarterly and monthly time series (p. 584).
smooth..................exponential smoothing (p. 590).
solve .....................solve a model (p. 594).
stats ......................descriptive statistics (p. 597).
switchreg ..............exogenous and Markov switching regression (p. 602).
testadd ..................likelihood ratio test for adding variables to equation (p. 606).
testdrop.................likelihood ratio test for dropping variables from equation (p. 607).
threshold ..............threshold least squares, including threshold autoregression and
smooth threshold autoregression (p. 607).
tsls........................estimate an equation using two-stage least squares regression
(p. 612).
uroot.....................unit root test (p. 619).
varest....................specify and estimate a VAR or VEC (p. 624).
varsel....................equation estimation using least squares with variable selection
(uni-directional, stepwise, swapwise, combinatorial, Auto-GETS,
Lasso) (p. 625).

Command Entries
The following section provides an alphabetical listing of commands. Each entry outlines the
command syntax and associated options, and provides examples and cross references.

addin Programming Commands

Register a program file as an EViews Add-in.

Syntax
addin(options) [path\]prog_name

registers the specified program file as an EViews Add-in. Note that the program file should
have a “.PRG” extension, which you need not specify in the prog_name.

If you do not provide the optional path specification, EViews looks for the program file in
the default EViews Add-ins directory.

Explicit path specifications containing “.\” and “..\” (to indicate the current level and one
directory level up) are evaluated relative the directory of the installer program in which the
366—Chapter 17.Command Reference

addin command is specified, or the EViews default directory if addin is run from the com-
mand line.

You may use the special “<addins>”directory keyword in your path specification.

Options
type=arg Specify the Add-ins type, where arg is the name of a
EViews object type. The default is to create a global Add-
in.
Specifying an object-specific Add-in using a matrix object
as in “type=matrix”, “type=vector”, etc. will register the
Add-in for all matrix object types (including coef, rowvec-
tor, and sym objects).
Sample objects do not support object-specific Add-ins so
that “type=sample” is not allowed.
proc=arg User--defined command/procedure name. If omitted, the
Add-in will not have a command form.
menu=arg Text for the Add-in menu entry. If omitted, the Add-in will
not have an associated menu item.
Note that you may use the “&” symbol in the entry text to
indicate that the following character should be used as a
menu shortcut.
desc=arg Brief description of the Add-in that will be displayed in the
Add-ins management dialog.
docs=arg Path and filename for the Add-in documentation. Determi-
nation of the path follows the rules specified above for the
addin filename.
version=arg Version number of the Add-in. If no version number is sup-
plied, EViews will assume version 1.0.

url=arg Specify the location of an XML file containing information


on the Add-in used for updating the Add-in to the latest
version. If not supplied, EViews will default to an XML file
hosted on the EViews website.
nowarn Removes the prompt warning that an add-in already exists
with the same name (and forces an overwrite of that add-
in).

Examples
addin(proc="myaddin", desc="This is my add-in", version="1.0")
.\myaddin.prg
adduo—367

registers the file “Myaddin.prg” as a global Add-in, with the user-defined global command
myaddin, no menu support, and no assigned documentation file. The description “This is
my add-in” will appear in the main Add-ins management dialog. The version number is
“1.0”. Note that the “.\” indicates the directory from which the program containing the
addin command was run, or the EViews default directory if addin is run interactively.
addin(type="graph", menu="Add US Recession Shading",
proc="recshade", docs=".\recession shade.txt", desc="Applies US
recession shading to a graph object.") .\recshade.prg

registers the file “Recshade.prg” as a graph specific Add-in. The Add-in supports the object-
command recshade, has an object-specific menu item “Add US Recession Shading”, and
has a documentation file “Recession shade.txt”.
addin(type=equation, menu="Simple rolling regression", proc=roll,
docs="<addins>\Roll\Roll.pdf", desc="Rolling Regression -
simple version", url="www.mysite.com/myaddins.xml",
version="1.2") "<addins>\Roll\roll.prg"

registers the Add-in file “Roll.prg” as an equation specific Add-in. Note that the documenta-
tion and program files are located in the “Roll” subdirectory of the default Add-ins directory.
The XML file located at www.mysite.com/myaddins.xml is used when checking for avail-
able updates for the Add-in, and the current version number is set to “1.2”.

Cross-references
See Chapter 8. “Add-ins,” on page 207 for a detailed discussion of Add-ins.

adduo Programming Commands

Register an EViews user object class.

Syntax
adduo(options) [path\]definition_name

registers the specified definition file as an EViews user object. Note that the definition file
should have a “.INI” extension.

If you do not provide the optional path specification, EViews looks for the program file in
the default EViews user objects directory.

Explicit path specifications containing “.\” and “..\” (to indicate the current level and one
directory level up) are evaluated relative the directory of the installer program in which the
adduo command is specified, or the EViews default directory if adduo is run from the com-
mand line.
368—Chapter 17.Command Reference

Options
name=arg Specify the name of the user object class.
desc=arg Brief description of the user object that will be displayed in
the user object management dialog.
docs=arg Path and filename for the user object documentation.
Determination of the path follows the rules specified above
for the adduo filename.
version=arg Version number of the Add-in. If no version number is sup-
plied, EViews will assume version 1.0.
url=arg Specify the location of an XML file containing information
on the Add-in used for updating the Add-in to the latest
version. If not supplied, EViews will default to an XML file
hosted on the EViews website.

Examples
adduo(name="roll", desc="Rolling Regression Object") .\rolldef.ini

registers the roll class of user object, specifying a description of “Rolling Regression Object”,
and using the definition file rolldef.ini, located in the same folder as the installer program.
adduo(name="resstore", version="1.0",
url="www.mysite.com/myuos.xml") .\resstoredef.ini

registers the resstore class of user object, specifying the version number as “1.0”, and using
the XML file located at “www.mysite.com/myuos.xml” to check for updates.

Cross-references
See Chapter 9. “User Objects,” on page 233 for a discussion of user objects.

arch Interactive Use Commands

Estimate generalized autoregressive conditional heteroskedasticity (GARCH) models.

Syntax
arch(p,q,options) y [x1 x2 x3] [@ p1 p2 [@ t1 t2]]
arch(p,q,options) y=expression [@ p1 p2 [@ t1 t2]]

The first two options specify the order of the GARCH model:
• The arch estimation method specifies a GARCH(p, q) model with p ARCH terms and q
GARCH terms. Note the order of the arguments in which the ARCH and GARCH terms
are entered.
arch—369

The maximum value for p or q is 9; values above will be set to 9. The minimum
value for p is 1. The minimum value for q is 0. If either p or q is not specified,
EViews will assume a corresponding order of 1. Thus, a GARCH(1, 1) is assumed by
default.
• For CGARCH, FIEGARCH and MIDAS-GARCH models, EViews only estimates (1,1)
models. For these specifications, p and q options should not be specified, and if pro-
vided, will be ignored.

After the “ARCH” keyword and options, specify the dependent variable followed by a list of
regressors in the mean equation.
• By default, only the intercept is included in the conditional variance equation. If you
wish to specify variance regressors, list them after the mean equation using an “@”-
sign to separate the mean from the variance equation.
• When estimating component ARCH models, you may specify exogenous variance
regressors for both the permanent and transitory components. After the mean equa-
tion regressors, first list the regressors for the permanent component, followed by an
“@”-sign, then the regressors for the transitory component. A constant term is always
included as a permanent component regressor.
• For MIDAS-GARCH models, the low-frequency permanent component regressor are
entered after the mean equation regressors and an “@”-sign. The regressor should be
specified as pagename\seriesname.

Options
Type Options
The default is to estimate a standard GARCH model. You may specify one of the followings
keywords to estimate a different model:
egarch Exponential GARCH.
parch[=arg] Power ARCH. If the optional arg is provided, the power
parameter will be set to that value, otherwise the power
parameter will be estimated.
cgarch Component (permanent and transitory) ARCH.
figarch Fractional GARCH (FIGARCH).
fiegarch Fractional Exponential GARCH (FIEGARCH(1,1)).
midas MIDAS GARCH(1,1)
370—Chapter 17.Command Reference

General Options
thrsh For Component GARCH models, include a threshold term.
thrsh=integer Number of threshold terms for GARCH models. The maxi-
(default=0) mum number of terms allowed is 9.
vt Variance target of the constant term for GARCH models.
(May not be used with integrated specifications.)
integrated Restrict GARCH model to be integrated, i.e. IGARCH. (May
not be used with variance targeting.)
asy=integer Number of asymmetric terms in Power ARCH or EGARCH
(default=1) models. The maximum number of terms allowed is 9.
trunclag=integer Number of terms in the expansion approximation for
(default=1000) FIGARCH and FIEGARCH models.
archm=arg ARCH-M (ARCH in mean) specification with the condi-
tional standard deviation (“archm=sd”), the conditional
variance (“archm=var”), or the log of the conditional vari-
ance (“archm= log”) entered as a regressor in the mean
equation.
tdist [=number] Estimate the model assuming that the residuals follow a
conditional Student’s t-distribution (the default is the con-
ditional normal distribution). Providing the optional num-
ber greater than two will fix the degrees of freedom to that
value. If the argument is not provided, the degrees of free-
dom will be estimated.
ged [=number] Estimate the model assuming that the residuals follow a
conditional GED (the default is the conditional normal dis-
tribution). Providing a positive value for the optional argu-
ment will fix the GED parameter. If the argument is not
provided, the parameter will be estimated.
z Turn of backcasting for both initial MA innovations and ini-
tial variances.
backcast=n Backcast weight to calculate value used as the presample
conditional variance. Weight needs to be greater than 0 and
less than or equal to 1; the default value is 0.7. Note that a
weight of 1 is equivalent to no backcasting, i.e. using the
unconditional residual variance as the presample condi-
tional variance.
optmethod = arg Optimization method: “bfgs” (BFGS); “newton” (Newton-
Raphson), “opg” or “bhhh” (OPG or BHHH), “legacy”
(EViews legacy).
“bfgs” is the default for new equations.
arch—371

optstep = arg Step method: “marquardt” (Marquardt - default); “dogleg”


(Dogleg); “linesearch” (Line search).
(Applicable when “optmethod=bfgs”, “optmethod=new-
ton” or “optmethod=opg”.)
b Use Berndt-Hall-Hall-Hausman (BHHH) as maximization
algorithm. The default is Marquardt.
(Applicable when “optmethod=legacy”.)
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method), “bollerslev”
(Bollerslev-Wooldridge method).
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian), “
(Applicable when non-legacy “optmethod=” with
“cov=ordinary”.)
h Bollerslev-Wooldridge robust quasi-maximum likelihood
(QML) covariance/standard errors.
(Applicable for “optmethod=legacy” when estimating
assuming normal errors.)
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients.
s Use the current coefficient values in “C” as starting values
(see also param (p. 564)).
s=number Specify a number between zero and one to determine start-
ing values as a fraction of preliminary LS estimates (out of
range values are set to “s=1”).
numericderiv / [Do / do not] use numeric derivatives only. If omitted,
-numericderiv EViews will follow the global default.
fastderiv / [Do / do not] use fast derivative computation. If omitted,
-fastderiv EViews will follow the global default.
Available only for legacy estimation (“optmeth=legacy”).
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
372—Chapter 17.Command Reference

coef=arg Specify the name of the coefficient vector (if specified by


list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print estimation results.

MIDAS Options
lag=arg Specify the number of lags of the low frequency regressor
to include. Default value is 32.
beta=arg Beta function restriction: none (“none”), trend coefficient
equals 1 (“trend”), endpoints coefficient equals 0 (“end-
point”), both trend and endpoints restriction (“both”). For
use when “midwgt=beta”. The default is “beta=none”.
thrsh Include a threshold term.
optmethod=arg Optimization method for nonlinear estimation: “bfgs”
(BFGS); “newton” Newton-Raphson), “opg”, “bhhh” (OPG
or BHHH), or “hybrid” (initial BHHH followed by BFGS).
Hybrid is the default method.
optstep=arg Step method for nonlinear estimation: “marquardt” (Mar-
quardt); “dogleg” (Dogleg); “linesearch” (Line search).
Marquardt is the default method.
cov=arg Covariance method for nonlinear models: “ordinary”
(default method based on inverse of the estimated informa-
tion matrix), “huber” or “white” (Huber-White sandwich).
covinfo=arg Information matrix method for nonlinear models: “opg”
(OPG); “hessian” (observed Hessian).
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
s Use the current coefficient values in estimator coefficient
vector as starting values in nonlinear estimation. If the
“s=number” or “s” options are not used, EViews will use
random starting values.
arch—373

s=number Determine starting values for nonlinear estimation. Specify


a number between zero and oSpecify the number of lags of
the low frequency regressor to include. Default value is
32.ne representing the fraction of preliminary EViews cho-
sen values. Note that out of range values are set to “s=1”.
Specifying “s=0” initializes coefficients to zero. If the
“s=number” or “s” options are not used, EViews will use
random starting values.
seed=positive_in- Seed the random number generator used in random start-
teger from 0 to ing values. If not specified, EViews will seed random num-
2,147,483,647 ber generator with a single integer draw from the default
global random number generator.
showopts/- [Do / do not] display the starting coefficient values and
showopts estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector; the default
behavior is to use the “C” coefficient vector.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Examples
arch(4, 0, m=1000, cov=bollerslev) sp500 c

estimates an ARCH(4) model with a mean equation consisting of the series SP500 regressed
on a constant. The procedure will perform up to 1000 iterations, and will report Bollerslev-
Wooldridge robust QML standard errors upon completion.

The commands:
c = 0.1
arch(thrsh=1, s, mean=var) @pch(nys) c ar(1)

estimate a TARCH(1, 1)-in-mean specification with the mean equation relating the percent
change of NYS to a constant, an AR term of order 1, and a conditional variance (GARCH)
term. The first line sets the default coefficient vector to 0.1, and the “s” option uses these
values as coefficient starting values.

The command:
arch(1, 2, asy=0, parch=1.5, ged=1.2) dlog(ibm)=c(1)+c(2)*
dlog(sp500) @ r

estimates a symmetric Power ARCH(2, 1) (autoregressive GARCH of order 2, and moving


average ARCH of order 1) model with GED errors. The power of model is fixed at 1.5 and the
GED parameter is fixed at 1.2. The mean equation consists of the first log difference of IBM
374—Chapter 17.Command Reference

regressed on a constant and the first log difference of SP500. The conditional variance equa-
tion includes an exogenous regressor R.

Cross-references
See Chapter 27. “ARCH and GARCH Estimation,” on page 1279 of User’s Guide II for a dis-
cussion of ARCH models.

See Equation::arch (p. 64) in the Object Reference for the equivalent object command.

archtest Interactive Use Commands

Test for autoregressive conditional heteroskedasticity (ARCH).

Carries out Lagrange Multiplier (LM) tests for ARCH in the residuals.

Note that a more general version of the ARCH test is available using Equation::archtest
(p. 70) as described in the Object Reference.

Syntax
archtest(options)

Options
You must specify the order of ARCH for which you wish to test. The number of lags to be
included in the test equation should be provided in parentheses after the arch keyword.
Other Options:
prompt Force the dialog to appear from within a program.
p Print output from the test.

Examples
ls output c labor capital
archtest(4)

Regresses OUTPUT on a constant, LABOR, and CAPITAL, and tests for ARCH up to order 4.
equation eq1.arch sp500 c
archtest(4)

Estimates a GARCH(1,1) model with mean equation of SP500 on a constant and tests for
additional ARCH up to order 4. Note that when performing an archtest after an arch esti-
mation, EViews uses the standardized residuals (the residual of the mean equation divided
by the estimated conditional standard deviation) to form the test.
ardl—375

Cross-references
See “ARCH LM Test” on page 1232 of User’s Guide II for further discussion of testing ARCH
and Chapter 27. “ARCH and GARCH Estimation,” on page 1279 of User’s Guide II for a dis-
cussion of working with ARCH models in EViews.

See Equation::archtest (p. 70) in the Object Reference for the equivalent object com-
mand. See Equation::hettest (p. 168) in the Object Reference for a more general version
of the ARCH test.

ardl Interactive Use Commands

Estimate an equation with autoregressive distributed lags using linear and nonlinear least
squares or quantile regression.

Syntax
equation.ardl(options) linear_regs [@ static_regs] [@asy dual_asymmetric_regs]
[@asylr long_run_asymmetric_regs] [@asysr short_run_asymmetric_regs]

The linear_regs specification is required:


• The linear_regs list should be the dependent variable followed by a list of linear dis-
tributed-lag regressors.

The remaining specifications are optional


• static_regs should be a list of static regressors, not including a constant or trend term.
• dual_asymmetric_regs are distributed-lag regressors which are asymmetric both in the
short-run and long-run.
• long_run_asymmetric_regs regressors are distributed lag-regressors which are asym-
metric in the long-run but symmetric in the short-run.
• short_run_asymmetric_regs are asymmetric regressors which are distributed lag-
regressors which are asymmetric in the short-run but symmetric in the long-run.

You may specify the lag for an individual distributed-lag variable using the
“@fl(variable, lag)” syntax. For instance, if the variable X should use 3 lags, irrespec-
tive of the fixed or automatic lag settings, you may specify this by entering “@fl(x, 3)” in the
regressor list.
376—Chapter 17.Command Reference

Options
Least Squares ARDL Options
method=arg Set the method of estimation: "ls" (least-squares regres-
(default = “ls”) sion, default) or "qreg" (quantile regression).
determ=arg Johansen deterministic trend type: “none” (no determinis-
(default = “rconst”) tics), “rconst” (restricted constant and no trend), “uconst”
(unrestricted constant and no trend), “rtrend” (unrestricted
constant and restricted trend, “utrend” (unrestricted con-
stant and unrestricted trend).
trend=arg Johansen deterministic trend type: “none” (no determinis-
(deprecated) tics), “const” (restricted constant and no trend, default),
“uconst” (unrestricted constant and no trend), “linear”
(unrestricted constant and restricted trend, “ulinear” (unre-
stricted constant and unrestricted trend).
Note: this is a deprecated s option which handles a subset
of cases covered by the “determ=” option
fixed Do not use automatic selection for lag lengths. This option
must be used with the “deplags=” and “reglags=”
options.
deplags=int Set the number of lags for the dependent variable to int. If
(default = 4) automatic selection is used, this sets the maximum number
of possible lags. If fixed lags are used (the fixed option is
set), this fixes the number of lags.
reglags=int (default Set the number of lags for the explanatory variables
= 4) (dynamic regressors) to int. If automatic selection is used,
this sets the maximum number of possible lags. If fixed
lags are used (the fixed option is set), this fixes the number
of lags for each regressor.
ic=key Set the method of automatic model selection. key may take
(default =“aic”) values of “aic” (Akaike information criterion, default),
“bic” (Schwarz criterion), “hq” (Hannan-Quinn criterion)
or “rbar2” (Adjusted R-squared, not applicable in panel
workfiles).
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method), “hac” (Newey-
West HAC, available for nonlinear least squares or ARMA
estimated by CLS)..
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
ardl—377

covlag=arg Whitening lag specification: integer (user-specified lag


(default=1) value), “a” (automatic selection).
covinfosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
covmaxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum
13
of T .
covkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
covbw=arg Kernel Bandwidth: “fixednw” (Newey-West fixed),
(default=“fixednw” “andrews” (Andrews automatic), “neweywest” (Newey-
) West automatic), number (User-specified bandwidth).
covnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric kernel bandwidth selection (if “covbw=newey-
west”).
covbwint Use integer portion of bandwidth.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print results.

Quantile ARDL Options


quant=number Quantile to be fit (where number is a value between 0 and
(default = 0.5) 1).
w=arg Weight series or expression.
Note: we recommend that, absent a good reason, you
employ the default settings Inverse std. dev. weights
(“wtype=istdev”) with EViews default scaling
(“wscale=eviews”) for backward compatibility with ver-
sions prior to EViews 7.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
378—Chapter 17.Command Reference

wscale=arg Weight scaling: EViews default (“eviews”), average


(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
cov=arg Method for computing coefficient covariance matrix: “iid”
(default=“sand- (ordinary estimates), “sandwich” (Huber sandwich esti-
wich”) mates), “boot” (bootstrap estimates).
When “cov=iid” or “cov=sandwich”, EViews will use the
sparsity nuisance parameter calculation specified in
“spmethod=” when estimating the coefficient covariance
matrix.
bwmethod=arg Method for automatically selecting bandwidth value for
(default = “hs”) use in estimation of sparsity and coefficient covariance
matrix: “hs” (Hall-Sheather), “bf” (Bofinger), “c” (Cham-
berlain).
bw =number Use user-specified bandwidth value in place of automatic
method specified in “bwmethod=”.
bwsize=number Size parameter for use in computation of bandwidth (used
(default = 0.05) when “bw=hs” and “bw=bf”).
spmethod=arg Sparsity estimation method: “resid” (Siddiqui using residu-
(default=“kernel”) als), “fitted” (Siddiqui using fitted quantiles at mean values
of regressors), “kernel” (Kernel density using residuals)
Note: “spmethod=resid” is not available when
“cov=sandwich”.
btmethod=arg Bootstrap method: “resid” (residual bootstrap), “pair” (xy-
(default= “pair”) pair bootstrap), “mcmb” (MCMB bootstrap), “mcmba”
(MCMB-A bootstrap).
btreps=integer Number of bootstrap repetitions
(default=100)
btseed=positive Seed the bootstrap random number generator.
integer If not specified, EViews will seed the bootstrap random
number generator with a single integer draw from the
default global random number generator.
btrnd=arg Type of random number generator for the bootstrap:
(default=“kn” or improved Knuth generator (“kn”), improved Mersenne
method previously Twister (“mt”), Knuth’s (1997) lagged Fibonacci generator
set using rndseed used in EViews 4 (“kn4”) L’Ecuyer’s (1999) combined mul-
(p. 577) in the tiple recursive generator (“le”), Matsumoto and
Command and Pro- Nishimura’s (1998) Mersenne Twister used in EViews 4
gramming Refer- (“mt4”).
ence).
ardl—379

btobs=integer Number of observations for bootstrap subsampling (when


“bsmethod=pair”).
Should be significantly greater than the number of regres-
sors and less than or equal to the number of observations
used in estimation. EViews will automatically restrict val-
ues to the range from the number of regressors and the
number of estimation observations.
If omitted, the bootstrap will use the number of observa-
tions used in estimation.
btout=name (optional) Matrix to hold results of bootstrap simulations.
k=arg Kernel function for sparsity and coefficient covariance
(default=“e”) matrix estimation (when “spmethod=kernel”): “e” (Epan-
echnikov), “r” (Triangular), “u” (Uniform), “n” (Normal–
Gaussian), “b” (Biweight–Quartic), “t” (Triweight), “c”
(Cosinus).
m=integer Maximum number of iterations.
s Use the current coefficient values in estimator coefficient
vector as starting values (see also param (p. 564) in the
Command and Programming Reference).
s=number (default Determine starting values for equations. Specify a number
=0) between 0 and 1 representing the fraction of preliminary
least squares coefficient estimates.
Note that out of range values are set to the default.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Examples
wfopen http://www.stern.nyu.edu/~wgreene/Text/Edition7/TableF5-
2.txt

opens example data from Greene (2008, page 685), containing quarterly US macroeconomic
variables between 1950 and 2000.

The following command


ardl(deplags=8, reglags=8) log(realcons) log(realgdp) @
@expand(@quarter, @droplast)
380—Chapter 17.Command Reference

creates an equation object and estimates an ARDL model with the log of real consumption
as the dependent variable, and the log of real GDP as a dynamic regressor. Quarterly dummy
variables are included as static regressors. Automatic model selection is used to determine
the number of lags of LOG(REALCONS) and LOG(REALGDP).

The command
ardl(deplags=3, reglags=3, fixed) log(realcons) log(realgdp) @
@expand(@quarter, @droplast)

estimates a second model, replicating Example 20.4 from Greene, with a fixed three lags of
the dependent variable and three lags of the regressor.
ardl(deplags=1, reglags=1, fixed) log(realcons) log(realgdp) @asy
log(realgovt)

The line above estimates an ARDL(1,1,1) model with the log of real consumption as the
dependent variable, the log of real GDP as a linear regressor, and log of real government
expenditures as a dual asymmetric regressor.
ardl(deplags=1, reglags=1, fixed) log(realcons) log(realgdp) @asy
log(realgovt) @asysr log(realinvs)

extends the previous model and estimates an ARDL(1,1,1,1) model by including the log of
real investments as a long-run asymmetric regressor.
ardl(deplags=1, reglags=1, fixed) log(realcons) log(realgdp) @asy
log(realgovt) @asysr log(realinvs) @asylr log(tbilrate)

The line above extends the previous model and estimates an ARDL(1,1,1,1,1) model by
including the log of treasury bill rates as a short-run asymmetric regressor.
wfopen oecd.wf1
ardl(fixed, deplags=1, reglags=1) log(cons) log(inf) log(inc)

This example estimates a panel ARDL model using the workfile “OECD.wf1”. This model
replicates that given in the original Pesaran, Shin and Smith 1999 paper. Model selection is
not used to choose the optimal lag lengths, rather a fixed single lag of both the dependent
variable and the regressor is employed.
ardl(method=qreg, ls=fixed, deplags=1, reglags=1, quant=0.4)
log(realcons) log(realgdp)

This command estimates a QARDL(1,1) model where lag selection is fixed for both the
dependent and independent regressors, and the quantile value is 0.4.

Cross-references
See Chapter 29. “ARDL and Quantile ARDL” of User’s Guide II for further discussion.
auto—381

auto Interactive Use Commands

Compute serial correlation LM (Lagrange multiplier) test.

Carries out Breusch-Godfrey Lagrange Multiplier (LM) tests for serial correlation in the esti-
mation residuals from the default equation.

Syntax
auto(order, options)

You must specify the order of serial correlation for which you wish to test. You should spec-
ify the number of lags in parentheses after the auto keyword, followed by any additional
options.

Options
prompt Force the dialog to appear from within a program.
p Print output from the test.

Examples
To regress OUTPUT on a constant, LABOR, and CAPITAL, and test for serial correlation of
up to order four you may use the commands:
ls output c labor capital
auto(4)

The commands:
output(t) c:\result\artest.txt
equation eq1.ls cons c y y(-1)
auto(12, p)

perform a regression of CONS on a constant, Y and lagged Y, and test for serial correlation of
up to order twelve. The first line redirects printed tables/text to the “Artest.TXT” file.

Cross-references
See “Serial Correlation LM Test” on page 1136 of User’s Guide II for further discussion of the
Breusch-Godfrey test.

See Equation::auto (p. 78) in the Object Reference for the corresponding equation view.
382—Chapter 17.Command Reference

binary Interactive Use Commands

Estimate binary dependent variable models.

Estimates models where the binary dependent variable Y is either zero or one (probit, logit,
gompit).

Syntax
binary(options) y x1 [x2 x3 ...]
binary(options) specification

Options
d=arg Specify likelihood: normal likelihood function, probit
(default=“n”) (“n”), logistic likelihood function, logit (“l”), Type I
extreme value likelihood function, Gompit (“x”).
optmethod = arg Optimization method: “bfgs” (BFGS); “newton” (Newton-
Raphson), “opg” or “bhhh” (OPG or BHHH), “legacy”
(EViews legacy).
Newton-Raphson is the default method.
optstep = arg Step method: “marquardt” (Marquardt); “dogleg” (Dog-
leg); “linesearch” (Line search).
Marquardt is the default method.
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method), “glm” (GLM
method).
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian - default).
(Applicable when non-legacy “optmethod=”.)
h Huber-White quasi-maximum likelihood (QML) standard
errors and covariances.
(Legacy option applicable when “optmethod=legacy”).
g GLM standard errors and covariances.
(Legacy option applicable when “optmethod=legacy”).
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
binary—383

s Use the current coefficient values in “C” as starting values


(see also param (p. 564)).
s=number Specify a number between zero and one to determine start-
ing values as a fraction of EViews default values (out of
range values are set to “s=1”).
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print results.

Examples
To estimate a logit model of Y using a constant, WAGE, EDU, and KIDS, and computing
Huber-White standard errors, you may use the command:
binary(d=l,cov=huber) y c wage edu kids

Note that this estimation uses the default global optimization options. The commands:
param c(1) .1 c(2) .1 c(3) .1
binary(s) y c x2 x3

estimate a probit model of Y on a constant, X2, and X3, using the specified starting values.
The commands:
coef beta_probit = @coefs
matrix cov_probit = @coefcov

store the estimated coefficients and coefficient covariances in the coefficient vector
BETA_PROBIT and matrix COV_PROBIT.

Cross-references
See “Binary Dependent Variable Models” on page 1431 of User’s Guide II for additional dis-
cussion.

See Equation::binary (p. 79) in the Object Reference for the corresponding equation
method.
384—Chapter 17.Command Reference

breakls Interactive Use Commands

Estimation by linear least squares regression with breakpoints.

Syntax
breakls(options) y z1 [z2 z3 ...] [@nv x1 x2 x3 ...]

List the dependent variable first, followed by a list of the independent variables that have
coefficients which are allowed to vary across breaks, followed optionally by the keyword
@nv and a list of non-varying coefficient variables.

Options
Breakpoint Options
method=arg Breakpoint selection method: “seqplus1” (sequential
(default=“seqplus1”) tests of single l  1 versus l breaks), “seqall” (sequen-
tial test of all possible l  1 versus l breaks), “glob”
(tests of global l vs. no breaks), “globplus1” (tests of
l  1 versus l globally determined breaks), “globinfo”
(information criteria evaluation), “user” (user-specified
break dates).
select=arg Sub-method setting (options depend on “method=”).
(1) if “method=glob”: Sequential (“seq”) (default),
Highest significant (“high”), UDmax (“udmax”),
WDmax (“wdmax”).
(2) if “method=globinfo”: Schwarz criterion (“bic” or
“sic”) (default), Liu-Wu-Zidek criterion (“lwz”).
trim=arg (default=5) Trimming percentage for determining minimum segment
size (5, 10, 15, 20, 25).
maxbreaks=integer Maximum number of breakpoints to allow (not applica-
(default=5) ble if “method=seqall”).
maxlevels=integer Maximum number of break levels to consider in sequen-
(default=5) tial testing (applicable when “method=sequall”).
breaks="arg" User-specified break dates entered in double quotes. For
use when “method=user”.
breakls—385

size=arg (default=5) Test sizes for use in sequential determination and final
test evaluation (10, 5, 2.5, 1) corresponding to 0.10,
0.05, 0.025, 0.01, respectively
heterr Assume regimes specific error distributions in variance
computation.
commondata Assume a common distribution for the data across seg-
ments (only applicable if original equation is estimated
with a robust covariance method, “heterr” is not speci-
fied).

General Options
w=arg Weight series or expression.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
cov=keyword Covariance type (optional): “white” (White diagonal
matrix), “hac” (Newey-West HAC).
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
covlag=arg Whitening lag specification: integer (user-specified lag
(default=1) value), “a” (automatic selection).
covinfosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
covmaxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum
13
of T .
covkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
386—Chapter 17.Command Reference

covbw=arg Kernel Bandwidth: “fixednw” (Newey-West fixed),


(default=“fixednw” “andrews” (Andrews automatic), “neweywest” (Newey-
) West automatic), number (User-specified bandwidth).
covnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric kernel bandwidth selection (if “covbw=newey-
west”).
covbwoffset=inte- Apply integer offset to bandwidth chosen by automatic
ger (default=0) selection method (“bw=andrews” or “bw=neweywest”).
covbwint Use integer portion of bandwidth chosen by automatic
selection method (“bw=andrews” or “bw=neweywest”).
coef=arg Specify the name of the coefficient vector; the default
behavior is to use the “C” coefficient vector.
prompt Force the dialog to appear from within a program.
p Print basic estimation results.

Examples
breakls m1 c unemp

uses the Bai-Perron sequential L  1 versus L tests to determine the optimal breaks in a
model regressing M1 on the breaking variables C and UNEMP.
breakls(method=glob, select=high) m1 c unemp

uses the global Bai-Perron L versus none tests to determine the breaks. The selected break
will be the highest significant number of breaks.
breakls(size=5, trim=10) m1 c unemp

lowers the sequential test size from 0.10 to 0.05, and raises the trimming to 10 percent.
breakls(method=user, break=”1990q1 2010q4”) m1 c @nv unemp

estimates the model with two user-specified break dates. In addition, the variable UNEMP is
restricted to have common coefficients across the regimes.

Cross-reference
See Chapter 34. “Least Squares with Breakpoints,” beginning on page 1541 of User’s Guide II
for discussion. See also “Multiple Breakpoint Tests” on page 1244 of User’s Guide II.

See Equation::multibreak (p. 207) of Object Reference for estimation of regression equa-
tions with breaks.
cause—387

cause Interactive Use Commands

Granger causality test.

Performs pairwise Granger causality tests between (all possible) pairs of the listed series or
group of series.

Syntax
cause(n, options) ser1 ser2 ser3

Following the keyword, list the series or group of series for which you wish to test for
Granger causality.

Options
You must specify the number of lags n to use for the test by providing an integer in paren-
theses after the keyword. Note that the regressors of the test equation are a constant and the
specified lags of the pair of series under test.
Other options:
prompt Force tcointehe dialog to appear from within a program.
p Print output of the test.

Examples
To compute Granger causality tests of whether GDP Granger causes M1 and whether M1
Granger causes GDP, you may enter the command:
cause(4) gdp m1

The regressors of each test are a constant and four lags of GDP and M1.
cause(12,p) m1 gdp r

prints the result of six pairwise Granger causality tests for the three series. The regressors of
each test are a constant and twelve lags of the two series under test (and do not include
lagged values of the third series).

Cross-references
See “Granger Causality” on page 712 of User’s Guide I for a discussion of Granger’s approach
to testing hypotheses about causality.

See also Group::cause (p. 441) in the Object Reference for the corresponding group view.
388—Chapter 17.Command Reference

ccopy Object Container, Data, and File Commands

Copy one or more series from the DRI Basic Economics database to EViews data bank
(.DB) files.

You must have the DRI database installed on your computer to use this feature.

Syntax
ccopy series_name

Type the name of the series or wildcard expression for series you want to copy after the
ccopy keyword. The data bank files will be stored in the default directory with the same
name as the series names in the DRI database. You can supply path information to indicate
the directory for the data bank files.

Examples
The command:
ccopy lhur

copies the DRI series LHUR to “Lhur.DB” file in the default path directory.
ccopy b:gdp c:\nipadata\gnet

copies the GDP series to the “Gdp.DB” file in the “B:” drive and the GNET series to the
“Gnet.DB” file in “c:\nipadata”.

Cross-references
See also cfetch (p. 391), clabel (p. 393), store (p. 600), fetch (p. 449).

cd Global Commands

Change default directory.

The cd command changes the current default working directory. The current working direc-
tory is displayed in the “Path=...” message in the bottom right of the EViews window.

Note that the default directory is not used for processing of include files (see include
(p. 349)).

Syntax
cd path_name
censored—389

Examples
To change the default directory to “sample data” in the “a:” drive, you may issue the com-
mand:
cd "a:\sample data"

Notice that the directory name is surrounded by double quotes. If your name does not con-
tain spaces, you may omit the quotes. The command:
cd a:\test

changes the default directory to “a:\test”.


cd “<myonedrive>:\test

changes the default directory to the cloud location, MYONEDRIVE.

Subsequent save operations will save into the default directory, unless you specify a differ-
ent directory at the time of the operation.

Cross-references
See Chapter 2. “Workfile Basics,” on page 29 of User’s Guide I for further discussion of basic
operations in EViews.

See also “include” on page 349, wfsave (p. 656), pagesave (p. 548), and save (p. 583).

censored Interactive Use Commands

Estimation of censored and truncated models.

Estimates models where the dependent variable is either censored or truncated. The allow-
able specifications include the standard Tobit model.

Syntax
censored(options) y x1 [x2 x3]
censored(options) specification

Options
l=number Set value for the left censoring limit.
(default=0)
r=number Set value for the right censoring limit.
(default=none)
l=series_name, i Set series name of the indicator variable for the left censor-
ing limit.
390—Chapter 17.Command Reference

r=series_name, i Set series name of the indicator variable for the right cen-
soring limit.
t Estimate truncated model.
d=arg Specify error distribution: normal (“n”), logistic (“l”), Type
(default=“n”) I extreme value (“x”).
optmethod = arg Optimization method: “bfgs” (BFGS); “newton” (Newton-
Raphson), “opg” or “bhhh” (OPG or BHHH), “legacy”
(EViews legacy).
Newton-Raphson is the default method.
optstep = arg Step method: “marquardt” (Marquardt); “dogleg” (Dog-
leg); “linesearch” (Line search).
Marquardt is the default method.
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method).
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian - default).
(Applicable when non-legacy “optmethod=”).
h Huber-White quasi-maximum likelihood (QML) standard
errors and covariances.
(Legacy option Applicable when “optmethod=legacy”).
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
s Use the current coefficient values in “C” as starting values
(see also param (p. 564)).
s=number Specify a number between zero and one to determine start-
ing values as a fraction of EViews default values (out of
range values are set to “s=1”).
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print results.
chdir—391

Examples
The command:
censored(cov=huber) hours c wage edu kids

estimates a censored regression model of HOURS on a constant, WAGE, EDU, and KIDS with
QML standard errors. This command uses the default normal likelihood, with left-censoring
at HOURS=0, no right censoring, and the quadratic hill climbing algorithm.

Cross-references
See Chapter 31. “Discrete and Limited Dependent Variable Models,” on page 1431 of User’s
Guide II for discussion of censored and truncated regression models.

See Equation::censored (p. 89) in the Object Reference for the corresponding equation
method.

cfetch Object Container, Data, and File Commands

Fetch a series from the DRI Basic Economics database into a workfile.

cfetch reads one or more series from the DRI Basic Economics Database into the active
workfile. You must have the DRI database installed on your computer to use this feature.

Syntax
cfetch series_name

Examples
cfetch lhur gdp gnet

reads the DRI series LHUR, GDP, and GNET into the current active workfile, performing fre-
quency conversions if necessary.

Cross-references
EViews’ automatic frequency conversion is described in “Frequency Conversion,” beginning
on page 177 of User’s Guide I.

See also ccopy (p. 388), clabel (p. 393), store (p. 600), fetch (p. 449).

chdir Global Commands

Change default directory.

See cd (p. 388).


392—Chapter 17.Command Reference

chow Interactive Use Commands

Chow test for stability.

Carries out Chow breakpoint or Chow forecast tests for parameter constancy.

Syntax
chow(options) obs1 [obs2 obs3 ...] @ x1 x2 x3

You must provide the breakpoint observations (using dates or observation numbers) to be
tested. To specify more than one breakpoint, separate the breakpoints by a space. For the
Chow breakpoint test, if the equation is specified by list and contains no linear terms, you
may specify a subset of the regressors to be tested for a breakpoint after an “@” sign.

Options
f Chow forecast test. For this option, you must specify a sin-
gle breakpoint to test (default performs breakpoint test).
p Print the result of test.

Examples
The commands:
ls m1 c gdp cpi ar(1)
chow 1970Q1 1980Q1

perform a regression of M1 on a constant, GDP, and CPI with first order autoregressive
errors, and employ a Chow breakpoint test to determine whether the parameters before the
1970’s, during the 1970’s, and after the 1970’s are “stable”.

To regress the log of SPOT on a constant, the log of P_US, and the log of P_UK, and to carry
out the Chow forecast test starting from 1973, enter the commands:
ls log(spot) c log(p_us) log(p_uk)
chow(f) 1973

To test whether only the constant term and the coefficient on the log of P_US prior to and
after 1970 are “stable” enter the commands:
chow 1970 @ c log(p_us)

Cross-references
See “Chow's Breakpoint Test” on page 1240 of User’s Guide II for further discussion.
close—393

See Equation::facbreak (p. 133), Equation::breaktest (p. 86), Equation::ubreak


(p. 258), and Equation::rls (p. 233) in the Object Reference for related equation object
views.

clabel Object Container, Data, and File Commands

Display a DRI Basic Economics database series description.

clabel reads the description of a series from the DRI Basic Economics Database and dis-
plays it in the status line at the bottom of the EViews window.

Use this command to verify the contents of a given DRI database series name. You must
have the DRI database installed on your computer to use this feature.

Syntax
clabel series_name

Examples
clabel lhur

displays the description of the DRI series LHUR on the status line.

Cross-references
See also ccopy (p. 388), cfetch (p. 391), read (p. 570), fetch (p. 449).

clearerrs Programming Commands

Set the current error count to 0.

May only be used in programs.

See also @errorcount (p. 877), seterrcount (p. 587), seterr (p. 587), and setmaxerrs
(p. 588).

close Object Container, Data, and File Commands

Close object, program, or workfile.

Closing an object eliminates its window. If the object is named, it is still displayed in the
workfile as an icon, otherwise it is deleted. Closing a program or workfile eliminates its win-
dow and removes it from memory. If a workfile has changed since you activated it, you will
see a dialog box asking if you want to save it to disk.
394—Chapter 17.Command Reference

Syntax
close option_or_name

Options
option_or_name may be either an object name or one of the following options:
@all Close down everything. This is the same as clicking on
Close All from the EViews main menu.
@objects Close down all objects. This is the same as clicking on
Close All Objects from the EViews main menu.
@wf Close down all open workfiles.
@db Close down all open databases.
@prg Close down all open program files.

Examples
close gdp graph1 table2

closes the three objects GDP, GRAPH1, and TABLE2.


lwage.hist
close lwage

opens the LWAGE window and displays the histogram view of LWAGE, then closes the win-
dow.
close @all

closes all windows within EViews.


close @objects

closes all objects in EViews, leaving workfiles, programs, and database windows open.

Cross-references
See Chapter 3. “Introduction,” on page 91 of User’s Guide I for a discussion of basic control
of EViews.

See also exit (p. 446) and save (p. 583).


coint—395

coint Interactive Use Commands

Perform either (1) Johansen’s system cointegration test, (2) Engle-Granger or Phillips-
Ouliaris single equation cointegration testing, or (3) Pedroni, Kao, or Fisher panel cointe-
gration testing for the specified series.

Syntax
There are three forms for the coint command which depend on the form of the test you
wish to perform:

Johansen Cointegration Test Syntax


coint(test_option, n, option) ser1 ser2 [...ser3 ser4 ...] [@ x1 x2 x3 ...]

uses the coint keyword followed by the test_option and the number of lags n, and if
desired, an “@”-sign followed by a list of exogenous variables. The first option must be one
of the following six test options:
a No deterministic trend in the data, and no intercept or
trend in the cointegrating equation.
b No deterministic trend in the data, and an intercept but no
trend in the cointegrating equation.
c Linear trend in the data, and an intercept but no trend in
the cointegrating equation.
d Linear trend in the data, and both an intercept and a trend
in the cointegrating equation.
e Quadratic trend in the data, and both an intercept and a
trend in the cointegrating equation.
s Summarize the results of all 5 options (a-e).

Options for the Johansen Test


restrict Impose restrictions as specified by the append (coint)
proc.
m = integer Maximum number of iterations for restricted estimation
(only valid if you choose the restrict option).
c = scalar Convergence criterion for restricted estimation. (only valid
if you choose the restrict option).
396—Chapter 17.Command Reference

save = mat_name Stores test statistics as a named matrix object. The save=
option stores a  k  1   4 matrix, where k is the num-
ber of endogenous variables in the VAR. The first column
contains the eigenvalues, the second column contains the
maximum eigenvalue statistics, the third column contains
the trace statistics, and the fourth column contains the log
likelihood values. The i-th row of columns 2 and 3 are the
test statistics for rank i – 1 . The last row is filled with
NAs, except the last column which contains the log likeli-
hood value of the unrestricted (full rank) model.
cvtype=ol Display 0.05 and 0.01 critical values from Osterwald-
Lenum (1992).
This option reproduces the output from version 4. The
default is to display critical values based on the response
surface coefficients from MacKinnon-Haug-Michelis
(1999). Note that the argument on the right side of the
equals sign are letters, not numbers 0-1).
cvsize=arg Specify the size of MacKinnon-Haug-Michelis (1999) criti-
(default=0.05) cal values to be displayed. The size must be between
0.0001 and 0.9999; values outside this range will be reset to
the default value of 0.05. This option is ignored if you set
“cvtype=ol”.
prompt Force the dialog to appear from within a program.
p Print results.

This type of cointegration testing may be used in a non-panel workfile. For Fisher combined
testing using the Johansen framework, see below. The remaining options for the Johansen
cointegration test are outlined below (“Options for the Johansen Test” on page 395).

Note that the output for cointegration tests displays p-values for the rank test statistics.
These p-values are computed using the response surface coefficients as estimated in MacK-
innon, Haug, and Michelis (1999). The 0.05 critical values are also based on the response
surface coefficients from MacKinnon-Haug-Michelis. Note: the reported critical values
assume no exogenous variables other than an intercept and trend.

Single Equation Test Syntax


coint(method=arg, options) ser1 ser2 [...ser3 ser4 ...] [@determ determ_spec] [@reg-
determ regdeterm_spec]

where
method=arg Test method: Engle-Granger residual test (“eg”), Phillips-
Ouliaris residual test (“po”).
coint—397

Cointegrating equation specifications that include a constant, linear, or quadratic trends,


should use the “trend=” option to specify those terms. If any of those terms are in the sto-
chastic regressors equations but not in the cointegrating equation, they should be specified
using the “regtrend=” option.

Deterministic trend regressors that are not covered by the list above may be specified using
the keywords @determ and @regdeterm. To specify deterministic trend regressors that enter
into the regressor and cointegrating equations, you should add the keyword @determ fol-
lowed by the list of trend regressors. To specify deterministic trends that enter in the regres-
sor equations but not the cointegrating equation, you should include the keyword
@regdeterm followed by the list of trend regressors.

Note that the p-values for the test statistics are based on simulations, and do not account for
any user-specified deterministic regressors.

This type of cointegration testing may be used in a non-panel workfile. The remaining
options for the single equation cointegration tests are outlined below.

Options for Single Equation Tests


Options for the Engle-Granger Test
The following options determine the specification of the Engle-Granger test (Augmented
Dickey-Fuller) equation and the calculation of the variances used in the test statistic.
trend=arg Specification for the powers of trend to include in the
(default=“const”) cointegrating equation: None (“none”), Constant (“const”),
Linear trend (“linear”), Quadratic trend (“quadratic”).
Note that the specification implies all trends up to the spec-
ified order so that choosing a quadratic trend instructs
EViews to include a constant and a linear trend term along
with the quadratic.
regtrend=arg Additional trends to include in the regressor equations (but
(default=“none”) not the cointegrating equation): None (“none”), Constant
(“const”), Linear trend (“linear”), Quadratic trend (“qua-
dratic”). Only trend orders higher than those specified by
“trend=” will be considered.
Note that the specification implies all trends up to the spec-
ified order so that choosing a quadratic trend instructs
EViews to include a constant and a linear trend term along
with the quadratic.
lag=arg Method of selecting the lag length (number of first differ-
(default=“a”) ence terms) to be included in the regression: “a” (auto-
matic information criterion based selection), or integer
(user-specified lag length).
398—Chapter 17.Command Reference

lagtype=arg Information criterion or method to use when computing


(default=“sic”) automatic lag length selection: “aic” (Akaike), “sic”
(Schwarz), “hqc” (Hannan-Quinn), “msaic” (Modified
Akaike), “msic” (Modified Schwarz), “mhqc” (Modified
Hannan-Quinn), “tstat” (t-statistic).
maxlag=integer Maximum lag length to consider when performing auto-
matic lag-length selection
14
default= int(min( T – k   3, 12)   T  100  )
where k is the number of coefficients in the cointegrating
equation. Applicable when “lag=a”.
lagpval=number Probability threshold to use when performing automatic
(default=0.10) lag-length selection using a t-test criterion. Applicable
when both “lag=a” and “lagtype=tstat”.
nodf Do not degree-of-freedom correct estimates of the vari-
ances.
prompt Force the dialog to appear from within a program.
p Print results.

Options for the Phillips-Ouliaris Test


The following options control the computation of the symmetric and one-sided long-run
variances in the Phillips-Ouliaris test.

Basic Options:
trend=arg Specification for the powers of trend to include in the
(default=“const”) cointegrating equation: None (“none”), Constant (“const”),
Linear trend (“linear”), Quadratic trend (“quadratic”).
Note that the specification implies all trends up to the spec-
ified order so that choosing a quadratic trend instructs
EViews to include a constant and a linear trend term along
with the quadratic.
regtrend=arg Additional trends to include in the regressor equations (but
(default=“none”) not the cointegrating equation): None (“none”), Constant
(“const”), Linear trend (“linear”), Quadratic trend (“qua-
dratic”). Only trend orders higher than those specified by
“trend=” will be considered.
Note that the specification implies all trends up to the spec-
ified order so that choosing a quadratic trend instructs
EViews to include a constant and a linear trend term along
with the quadratic.
coint—399

nodf Do not degree-of-freedom correct the coefficient covariance


estimate.
prompt Force the dialog to appear from within a program.
p Print results.

HAC Whitening Options:


lag=arg (default=0) Lag specification: integer (user-specified lag value), “a”
(automatic selection).
infosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
maxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum.

HAC Kernel Options:


kern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
bw=arg Bandwidth: “fixednw” (Newey-West fixed), “andrews”
(default=“nwfixed”) (Andrews automatic), “neweywest” (Newey-West auto-
matic), number (User-specified bandwidth).
nwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric bandwidth selection (if “bw=neweywest”).
bwint Use integer portion of bandwidth.

Panel Syntax
coint(option) ser1 ser2 [...ser3 ser4 ...]

The coint command tests for cointegration among the series in the group. The second form
of the command should be used with panel structured workfiles.

Options for the Panel Tests


For panel cointegration tests, you may specify the type using one of the following keywords:
400—Chapter 17.Command Reference

Pedroni (default) Pedroni (1994 and 2004).


Kao Kao (1999)
Fisher Fisher - pooled Johansen

Depending on the type selected above, the following may be used to indicate deterministic
trends:
const (default) Include a constant in the test equation.
Applicable to Pedroni and Kao tests.
trend Include a constant and a linear time trend in the test equa-
tion.
Applicable to Pedroni tests.
none Do not include a constant or time trend.
Applicable to Pedroni tests.
a, b, c, d, or e Indicate deterministic trends using the “a”, “b”, “c”, “d”,
and “e” keywords, as detailed above in “Options for the
Johansen Test” on page 395.
Applicable to Fisher tests.

Additional Options:
ac=arg Method of estimating the frequency zero spectrum: “bt”
(default=“bt”) (Bartlett kernel), “pr” (Parzen kernel), “qs” (Quadratic
Spectral kernel).
Applicable to Pedroni and Kao tests.
band=arg Method of selecting the bandwidth, where arg may be
(default=“nw”) “nw” (Newey-West automatic variable bandwidth selec-
tion), or a number indicating a user-specified common
bandwidth.
Applicable to Pedroni and Kao tests.
lag=arg For Pedroni and Kao tests, the method of selecting lag
length (number of first difference terms) to be included in
the residual regression. For Fisher tests, a pair of numbers
indicating lag.
infosel=arg Information criterion to use when computing automatic lag
(default=“sic”) length selection: “aic” (Akaike), “sic” (Schwarz), “hqc”
(Hannan-Quinn).
Applicable to Pedroni and Kao tests.
coint—401

maxlag=int Maximum lag length to consider when performing auto-


matic lag length selection, where int is an integer. The
default is
14
int(min  T i  3, 12    T i  100  )
where T i is the length of the cross-section.
Applicable to Pedroni and Kao tests.
disp=arg Maximum number of individual results to be displayed.
(default=500)
prompt Force the dialog to appear from within a program.
p Print results.

Examples
Johansen test
coint(s,4) x y z

summarizes the results of the Johansen cointegration test for the series X, Y, and Z for all
five specifications of trend. The test equation uses lags of up to order four.
Engle-Granger Test
coint(method=eg) x y z

performs the default Engle-Granger test on the residuals from a cointegrating equation
which includes a constant. The number of lags is determined using the SIC criterion and an
observation-based maximum number of lags.
coint(method=eg, trend=linear, lag=a, lagtype=tstat, lagpval=.15,
maxlag=10) x y z

employs a cointegrating equation that includes a constant and linear trend, and uses a
sequential t-test starting at lag 10 with threshold probability 0.15 to determine the number
of lags.
coint(method=eg, lag=5) x y z

conducts an Engle-Granger cointegration test on the residuals from a cointegrating equation


with a constant, using a fixed lag of 5.
Phillips-Ouliaris Test
coint(method=po) x y z

performs the default Phillips-Ouliaris test on the residuals from a cointegrating equation
with a constant, using a Bartlett kernel and Newey-West fixed bandwidth.
coint(method=po, bw=andrews, kernel=quadspec, nodf) x y z
402—Chapter 17.Command Reference

estimates the long-run covariances using a Quadratic Spectral kernel, Andrews automatic
bandwidth, and no degrees-of-freedom correction.
coint(method=po, trend=linear, lag=1, bw=4) x y z

estimates a cointegrating equation with a constant and linear trend, and performs the Phil-
lips-Ouliaris test on the residuals by computing the long-run covariances using AR(1) pre-
whitening, a fixed bandwidth of 4, and the Bartlett kernel.
Panel Tests
For a panel structured workfile,
coint(pedroni,maxlag=3,infosel=sic) x y z

performs Pedroni’s residual-based panel cointegration test with automatic lag selection with
a maximum lag limit of 3. Automatic selection based on Schwarz criterion.

Cross-references
See Chapter 59. “Cointegration Testing,” on page 2467 of User’s Guide II for details on the
various cointegration tests.

See Equation::coint (p. 97) and Group::coint (p. 444) in the Object Reference for the
related object routines.

cointreg Interactive Use Commands

Estimate a cointegrating equation using Fully Modified OLS (FMOLS), Canonical Cointe-
grating Regression (CCR), or Dynamic OLS (DOLS) in single time series settings, and Panel
FMOLS and DOLS in panel workfiles.

Syntax
cointreg(options) y x1 [x2 x3 ...] [@determ determ_spec] [@regdeterm regdeter-
m_spec]

List the coint keyword, followed by the dependent variable and a list of the cointegrating
variables.

Cointegrating equation specifications that include a constant, linear, or quadratic trends,


should use the “trend=” option to specify those terms. If any of those terms are in the sto-
chastic regressors equations but not in the cointegrating equation, they should be specified
using the “regtrend=” option.

Deterministic trend regressors that are not covered by the list above may be specified using
the keywords @determ and @regdeterm. To specify deterministic trend regressors that enter
into the regressor and cointegrating equations, you should add the keyword @determ fol-
lowed by the list of trend regressors. To specify deterministic trends that enter in the regres-
cointreg—403

sor equations but not the cointegrating equation, you should include the keyword
@regdeterm followed by the list of trend regressors.

Basic Options
method=arg Estimation method: Fully Modified OLS (“fmols”), Canoni-
(default=“fmols”) cal Cointegrating Regression (“ccr”), Dynamic OLS (“dols”)
Note that CCR estimation is not available in panel settings.
trend=arg Specification for the powers of trend to include in the
(default=“const”) cointegrating and regressor equations: None (“none”),
Constant (“const”), Linear trend (“linear”), Quadratic trend
(“quadratic”).
Note that the specification implies all trends up to the spec-
ified order so that choosing a quadratic trend instructs
EViews to include a constant and a linear trend term along
with the quadratic.
regtrend=arg Additional trends to include in the regressor equations (but
(default=“none”) not the cointegrating equation): None (“none”), Constant
(“const”), Linear trend (“linear”), Quadratic trend (“qua-
dratic”). Only trend orders higher than those specified by
“trend=” will be considered.
Note that the specification implies all trends up to the spec-
ified order so that choosing a quadratic trend instructs
EViews to include a constant and a linear trend term along
with the quadratic.
regdiff Estimate the regressor equation innovations directly using
the difference specifications.
coef=arg Specify the name of the coefficient vector; the default
behavior is to use the “C” coefficient vector.
prompt Force the dialog to appear from within a program.
p Print results.

In addition to these options, there are specialized options for each estimation method.

Panel Options
panmethod=arg Panel estimation method: pooled (“pooled”), pooled
(default=“pooled”) weighted (“weighted”), grouped (“grouped”)
pancov=sandwich Estimate the coefficient covariance using a sandwich
method that allows for cross-section heterogeneity.
404—Chapter 17.Command Reference

Options for FMOLS and CCR


To estimate FMOLS or CCR use the “method=fmols” or “method=ccr” options. The follow-
ing options control the computation of the symmetric and one-sided long-run covariance
matrices and the estimate of the coefficient covariance.
HAC Whitening Options

lag=arg (default=0) Lag specification: integer (user-specified lag value), “a”


(automatic selection).
infosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
maxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum.

HAC Kernel Options

kern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),


(default=“bart”) “bohman” (Bohman), “daniell” (Daniell), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
bw=arg Bandwidth:: “fixednw” (Newey-West fixed), “andrews”
(default=“nwfixed”) (Andrews automatic), “neweywest” (Newey-West auto-
matic), number (User-specified bandwidth).
nwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric bandwidth selection (if “bw=neweywest”).
bwoffset=integer Apply integer offset to bandwidth chosen by automatic
(default=0) selection method (“bw=andrews” or “bw=neweywest”).
bwint Use integer portion of bandwidth chosen by automatic
selection method (“bw=andrews” or “bw=neweywest”).

Coefficient Covariance

nodf Do not degree-of-freedom correct the coefficient covariance


estimate.
cointreg—405

Panel Options

hetfirst Estimate the first-stage regression assuming heterogeneous


coefficients. For FMOLS specifications estimated using
pooled or pooled weighted methods
(“panmethod =pooled”, “panmethod=weighted”)

Options for DOLS


To estimate using DOLS use the “method=dols” option. The following options control the
specification of the lags and leads and the estimate of the coefficient covariance.

lltype=arg Lag-lead method: fixed values (“fixed”), automatic selec-


(default=“fixed”) tion - Akaike (“aic”), automatic - Schwarz (“sic”), auto-
matic - Hannan-Quinn (“hqc”), None (“none”).
lag=arg Lag specification: integer (required user-specified number
of lags if “lltype=fixed”).
lead=arg Lead specification: integer (required user-specified number
of lags if “lltype=fixed”).
maxll=integer Maximum lag and lead-length for automatic selection
(optional user-specified integer if “lltype=” is used to
specify automatic selection). The default is an observation-
based maximum.
cov=arg Coefficient covariance method: (default) long-run variance
scaled OLS, unscaled OLS (“ols”), White (“white”),
Newey-West (“hac”).
nodf Do not degree-of-freedom correct the coefficient covariance
estimate.

For the default covariance calculation or “cov=hac”, the following options control the com-
putation of the long-run variance or robust covariance:
HAC Covariance Whitening Options (if default covariance or “cov=hac”)

covlag=arg Lag specification: integer (user-specified lag value), “a”


(default=0) (automatic selection).
covinfosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
covmaxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum.
406—Chapter 17.Command Reference

HAC Covariance Kernel Options (if default covariance or “cov=hac”)

covkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),


(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
covbw=arg Bandwidth: “fixednw” (Newey-West fixed), “andrews”
(default=“nwfixed”) (Andrews automatic), “neweywest” (Newey-West auto-
matic), number (User-specified bandwidth).
covnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric bandwidth selection (if “covbw=neweywest”).
covbwoffset=integer Apply integer offset to bandwidth chosen by automatic
(default=0) selection method (“bw=andrews” or “bw=neweywest”).
covbwint Use integer portion of bandwidth chosen by automatic
selection method (“bw=andrews” or “bw=neweywest”).

Panel Options
Weighted coefficient or coefficient covariance estimation in panel DOLS requires individual
estimates of the long-run variances of the residuals. You may compute these estimates using
the standard default long-run variance options, or you may choose to estimate it using the
ordinary variance.

For weighted estimation we have:


panwgtlag=arg Lag specification: integer (user-specified lag value), “a”
(default=0) (automatic selection).
panwgtinfosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lrvarlag=a”).
panwgtmaxlag=inte- Maximum lag-length for automatic selection (optional) (if
ger “lrvarlag=a”). The default is an observation-based maxi-
mum.
panwgtkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniell), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
cointreg—407

panwgtbw=arg Bandwidth:: “fixednw” (Newey-West fixed), “andrews”


(default=“nwfixed”) (Andrews automatic), “neweywest” (Newey-West auto-
matic), number (User-specified bandwidth).
panwgtnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric bandwidth selection (if “bw=neweywest”).
panwgtbwoff- Apply offset to automatically selected bandwidth.
set=integer For settings where “cov=hac”, “covkern=” is specified,
(default=0) and “covbw=” is not user-specified.
panwgtbwint Use integer portion of bandwidth chosen by automatic
selection method (“bw=andrews” or “bw=neweywest”).

For the coefficient covariance estimation we have:


lrvar=ordinary Compute DOLS estimates of the long-run residual variance
used in covariance calculation using the ordinary variance.
lrvarlag=arg For DOLS estimates of the long-run residual variance used
(default=0) in covariance calculation, lag specification: integer (user-
specified lag value), “a” (automatic selection).
lrvarinfosel=arg For DOLS estimates of the long-run residual variance used
(default=“aic”) in covariance calculation, information criterion for auto-
matic selection: “aic” (Akaike), “sic” (Schwarz), “hqc”
(Hannan-Quinn) (if “lrvarlag=a”).
lrvarmaxlag=integer For DOLS estimates of the long-run residual variance used
in covariance calculation, maximum lag-length for auto-
matic selection (optional) (if “lrvarlag=a”). The default is
an observation-based maximum.
lrvarkern=arg For DOLS estimates of the long-run residual variance used
(default=“bart”) in covariance calculation, Kernel shape: “none” (no ker-
nel), “bart” (Bartlett, default), “bohman” (Bohman), “dan-
iell” (Daniell), “parzen” (Parzen), “parzriesz” (Parzen-
Riesz), “parzgeo” (Parzen-Geometric), “parzcauchy”
(Parzen-Cauchy), “quadspec” (Quadratic Spectral), “trunc”
(Truncated), “thamm” (Tukey-Hamming), “thann” (Tukey-
Hanning), “tparz” (Tukey-Parzen).
lrvarbw=arg For DOLS estimates of the long-run residual variance used
(default=“nwfixed”) in covariance calculation, bandwidth:: “fixednw” (Newey-
West fixed), “andrews” (Andrews automatic), “neweywest”
(Newey-West automatic), number (User-specified band-
width).
408—Chapter 17.Command Reference

lrvarnwlag=integer For DOLS estimates of the long-run residual variance used


in covariance calculation, Newey-West lag-selection param-
eter for use in nonparametric bandwidth selection (if
“bw=neweywest”).
lrvarbwoffset=inte- For DOLS estimates of the long-run residual variance used
ger (default=0) in covariance calculation, apply offset to automatically
selected bandwidth.
For settings where “cov=hac”, “covkern=” is specified,
and “covbw=” is not user-specified.
lrvarbwint For DOLS estimates of the long-run residual variance used
in covariance calculation, use integer portion of band-
width.

Examples
FMOLS and CCR
To estimate, by FMOLS, the cointegrating equation for LC and LY including a constant, you
may use:
cointreg(nodf, bw=andrews) lc ly

The long-run covariances are estimated nonparametrically using a Bartlett kernel and a
bandwidth determined by the Andrews automatic selection method. The coefficient covari-
ances are estimated with no degree-of-freedom correction.

To include a linear trend term in a model where the long-run covariances computed using
the Quadratic Spectral kernel and a fixed bandwidth of 10, enter:
cointreg(trend=linear, nodf, bw=10, kern=quadspec) lc ly

A model with a cubic trend may be estimated using:


cointreg(trend=linear, lags=2, bw=neweywest, nwlag=10,
kernel=parzen) lc ly @determ @trend^3

Here, the long-run covariances are estimated using a VAR(2) prewhitened Parzen kernel
with Newey-West nonparametric bandwidth determined using 10 lags in the autocovariance
calculations.
cointreg(trend=quadratic, bw=andrews, lags=a, infosel=aic,
kernel=none, regdiff) lc ly @regdeterm @trend^3

estimates a restricted model with a cubic trend term that does not appear in the cointegrat-
ing equation using a parametric VARHAC with automatic lag length selection based on the
AIC. The residuals for the regressors equations are obtained by estimating the difference
specification.

To estimate by CCR, we provide the “method=ccr” option. The command


cointreg—409

cointreg(method=ccr, lag=2, bw=andrews, kern=quadspec) lc ly

estimates, by CCR, the constant only model using a VAR(2) prewhitened Quadratic Spectral
and Andrews automatic bandwidth selection.
cointreg(method=ccr, trend=linear, lag=a, maxlag=5, bw=andrews,
kern=quadspec) lc ly

modifies the previous estimates by adding a linear trend term to the cointegrating and
regressors equations, and changing the VAR prewhitening to automatic selection using the
default SIC with a maximum lag length of 5.
cointreg(method=ccr, trend=linear, regtrend=quadratic, lag=a,
maxlag=5, bw=andrews) lc ly

adds a quadratic trend term to the regressors equations only, and changes the kernel to the
default Bartlett.
DOLS
cointreg(method=dols, trend=linear, nodf, lag=4, lead=4) lc ly

estimates the linear specification using DOLS with four lags and leads. The coefficient cova-
riance is obtained by rescaling the no d.f.-correction OLS covariance using the long-run vari-
ance of the residuals computed using the default Bartlett kernel and default fixed Newey-
West bandwidth.
cointreg(method=dols, trend=quadratic, nodf, lag=4, lead=2,
covkern=bohman, covbw=10) lc ly @determ @trend^3

estimates a cubic specification using 4 lags and 2 leads, where the coefficient covariance
uses a Bohman kernel and fixed bandwidth of 10.
cointreg(method=dols, trend=quadratic, nodf, lag=4, lead=2,
cov=hac, covkern=bohman, covbw=10) lc ly @determ @trend^3

estimates the same specification using a HAC covariance in place of the scaled OLS covari-
ance.
cointreg(method=dols, trend=quadratic, lltype=none, cov=ols) lc ly
@determ @trend^3

computes the Static OLS estimates with the usual OLS d.f. corrected coefficient covariance.

Cross-references
See Chapter 28. “Cointegrating Regression,” beginning on page 1319 of User’s Guide II for a
discussion of single equation cointegrating regression. See Chapter 57. “Panel Cointegration
Estimation,” beginning on page 2413 of User’s Guide II for discussion of estimation in panel
settings.

See “Technical Discussion” on page 1986 of User’s Guide II for a discussion of VEC estima-
tion.
410—Chapter 17.Command Reference

See also coint (p. 395).

colplace Matrix Utility Commands

Place vector in column of a matrix.

Place a column or rowvector object in a specified column of a matrix.

Syntax
colplace(m, r, n)

Places the column vector or rowvector v into the matrix m at column n. The number of rows
of m and v must match, and the destination column must already exist within m.

Examples
matrix m1 = @mnrnd(30, 5)
vector v1 = @mnrnd(30)
colplace(m1, v1, 3)

The third column of M1 will be set equal to the vector V1.

Cross-references
See also rowplace (p. 581) and matplace (p. 518).

commandcap Programming Commands

Add comment to command capture window.

Syntax
commandcap arg

sends arg to the command capture window. Of particular use to add-in writers for sending
notifications to users.

Cross-references
See “Command Capture” on page 2545 of the User’s Guide I for further details.

See also statusline (p. 598).


copy—411

copy Object Container, Data, and File Commands

Copy an object, or a set of objects matching a name pattern, within and between workfiles,
workfile pages, and databases. Data in series objects may be frequency converted or match
merged.

Syntax
copy(options) src_spec dest_spec [src_id dest_id]
copy(options) src_spec dest_spec [@src src_ids @dest dest_id]

where src_spec and dest_spec are of the form:


[ctype][container::][page\]object_name

There are three parts to the copy command: (1) a specification of the location and names of
the source objects; (2) a specification of the location and names of the destination objects;
(3) optional source and destination IDs if the copy operation involves match merging.

The source and destination objects are specified in multiple (optional) parts: (1) the con-
tainer specification is the name of a workfile or database; (2) the page specification is the
name of a page within a workfile or a subdirectory within a database; and (3) the
object_name specification is the name of an object or a wildcard pattern corresponding to
multiple objects.

The ctype specification is rarely required, but permits you to specify precisely your source or
destination in cases where a database and workfile share the same name. In this case,
ctype may be used to indicate the container to which you are referring by prefixing the con-
tainer name with “:” to indicate the workfile, or “::” to indicate the database with the com-
mon name.

When parts of the source or destination specification are not provided, EViews will fill in
default values where possible. The default container is the active workfile, unless the “::”
prefix is used in which case the default container is the default database. The default page
within a workfile is always the active page. The default name for the destination object is
the name of the object within the source container.

If ID series are not provided in the command, then EViews will perform frequency conver-
sion when copying data whenever the source and destination containers have different fre-
quencies. If ID series are provided, then EViews will perform a general match merge
between the source and destination using the specified ID series. In the case where you wish
to copy your data using match merging with special treatment for date matching, you must
use the special keyword “@DATE” as an ID series for the source or destination. If “@DATE”
is not specified as an identifier in either the source or destination IDs, EViews will perform
an exact match merge using the given identifiers.
412—Chapter 17.Command Reference

If ID series are not specified, but a conversion option requiring a general match merge is
used (e.g., “c=med”), “@DATE @DATE” will be appended to the list of IDs and a general
date match merge will be employed.

See Link::linkto (p. 530) in the Object Reference for additional discussion of the differ-
ences embodied in these choices.

The general syntax described above covers all possible uses of the copy command. The fol-
lowing paragraphs provide examples of the specific syntax used for some common cases of
the command.

Copying Within a Workfile


Copy an object within the default workfile page as a new object with a different name:
• copy(options) src_name dest_name

Copy an object from the src_page page into the default workfile page using the specified
name:
• copy(options) src_page\src_name dest_name

Copy an object from the src_page page into the dest_page page, keeping the same name:
• copy(options) src_page\src_names dest_page\

Copy an object from the src_page page to the default workfile page, match merging any
series data using a single src_id and a single dest_id identifier series:
• copy(options) src_page\src_name dest_name src_id dest_id

Copy an object from the src_page page to the dest_page match merging any series data using
multiple source and destination identifier series:
• copy(options) src_page\src_name dest_page\dest_name @src src_id1 src_id2 ...
src_id_n @dest dest_id1 dest_id2 ... dest_id_n

Copying Between Containers (Workfiles and Databases)


Copy one or more objects from the src_page of the workfile src_workfile to the dest_page of
the workfile dest_workfile, using the name or name pattern given in src_names:
• copy(options) src_workfile::src_page\src_names dest_workfile::dest_page\

Copy an object from database src_database to the default page in the container dest_con-
tainer:
• copy(options) src_database::src_name dest_container::dest_name
copy—413

Note that if both a workfile and database exist matching the name provided in dest_con-
tainer, EViews will favor the workfile unless the “::” prefix is used to specify explicitly that
the database should be used.

Options
Basic Options

overwrite / o Overwrite any existing object with the destination name in


the destination container. Error only if a non-editable series
is encountered in the destination location.
merge / m If the source object is a series, merge the data from the
source series into any existing destination series, preserv-
ing any values in the destination series that are not present
in the source. For all other object types, overwrite any
existing object with the source object. Error if a non-edit-
able series is encountered in the destination location.
protect / p Protect objects in the destination location from overwriting
or merging. If there is an existing object in the destination
container, cancel the copy operation for that object, but do
not generate an error.
noerr Suppress errors that are generated during the copy. For
example, if the overwrite option is used, suppress any error
caused by attempting to overwrite a non-editable series
such as an index series used in the workfile structure.
link Link the object to the source data so that the values can be
refreshed at a later time.

Group Copy Options


When copying a group object from workfile to database:
g=arg Method for copying group objects from a workfile to data-
base: “s” (copy group definition and series as separate
objects), “t” (copy group definition and series as one
object), “d” (copy series only as separate objects), “l”
(copy group definition only).

When copying a group object from a database to a workfile:


g=arg Method for copying group objects from a database or work-
file to a workfile: “b” (copy both group definition and
series), “d” (copy only the series), “l” (copy only the group
definition).
414—Chapter 17.Command Reference

Note that copying a group object containing expressions or auto-updating series between
workfiles only copies the expressions, and not the underlying series.
Frequency Conversion Options
If the copy command does not specify identifier series, EViews will perform frequency con-
version of the data contained in series objects whenever the source and destination contain-
ers are dated, but do not have the same frequency.

If either of the pages are undated, EViews will, unless match merge options are provided (as
described below), perform a raw copy, in which the first observation in the source workfile
page is copied into the first observation in the destination page, the second observation in
the source into the second observation in the destination, and so forth.

The following options control the frequency conversion method when copying series and
group objects into a workfile page and converting from low to high frequency:
c=arg Low to high conversion methods: “r” or “repeata” (con-
stant match average), “d” or “repeats” (constant match
sum), “q” or “quada” (quadratic match average), “t” or
“quads” (quadratic match sum), “linearf” (linear match
first), “i” or “linearl” (linear match last), “cubicf” (cubic
match first), “c” or “cubicl” (cubic match last), “pointf”
(point first), “pointl” (point last), “dentonf” (Denton first),
“dentonl” (Denton last), “dentona” (Denton average),
“dentons” (Denton sum), “chowlinf” (Chow-Lin first),
“chowlinl” (Chow-Lin last), “chowlina” (Chow-Lin aver-
age),“chowlins” (Chow-Lin sum), “litmanf” (Litterman
first), “litmanl” (Litterman last), “litmana” (Litterman
average), “litmans” (Litterman sum).
rho=arg Autocorrelation coefficient (for Chow-Lin and Litterman
conversions). Must be between 0 and 1, inclusive.

In addition, for Denton, Chow-Lin, and Litterman conversions, you must specify the indica-
tor series by appending the keyword “@indicator” followed by the series name at the end of
the copy command.

The following options control the frequency conversion method when copying series and
group objects into a workfile page and converting from high to low frequency:
copy—415

c=arg High to low conversion methods removing NAs: “a” (aver-


age of the nonmissing observations), “s” (sum of the non-
missing observations), “f” (first nonmissing observation),
“l” (last nonmissing observation), “x” (maximum nonmiss-
ing observation), “m” (minimum nonmissing observation).
High to low conversion methods propagating NAs: “an” or
“na” (average, propagating missings), “sn” or “ns” (sum,
propagating missings), “fn” or “nf” (first, propagating
missings), “ln” or “nl” (last, propagating missings), “xn”
or “nx” (maximum, propagating missings), “mn” or “nm”
(minimum, propagating missings).

Note that if no conversion method is given in the command, the conversion method speci-
fied within the series object will be used as the default. If the series does not contain an
explicit conversion method, the global option settings will used to determine the method.

Frequency conversion involving panel structured pages involves special handling:


• If both pages are dated panel pages that are structured with a single identifier, EViews
will perform frequency conversion cross-section by cross-section.
• Conversion from a dated panel page to a dated, non-panel page will first perform a
mean contraction across cross-sections to obtain a single time series (by computing
the means for each period), and then a frequency conversion of the resulting time
series to the new frequency.
• Conversion from a dated, non-panel page to a dated panel page will first involve a fre-
quency conversion of the single time series to the new frequency. The converted time
series will be used for each cross-section in the panel page.

In all three of these cases, all of the high-to-low conversion methods are supported, but low-
to-high frequency conversion only offers Constant-match average (repeating of the low fre-
quency observations).

Lastly, conversion involving a panel page with more than one dimension or an undated page
will default to raw data copy unless general match merge options are provided.
Match Merge Options
These options are available when ID series are specified in the copy commmand.
416—Chapter 17.Command Reference

smpl= Sample to be used when computing contractions during


smpl_spec copying using match merge. Either provide the sample
range in double quotes or specify a named sample object.
By default, EViews will use the entire workfile sample
“@ALL”.
c=arg Set the match merge contraction method.
If you are copying a numeric source series by general
match merge, the argument can be one of: “mean”, “med”
(median), “max”, “min”, “sum”, “sumsq” (sum-of-
squares), “var” (variance), “sd” (standard deviation),
“skew” (skewness), “kurt” (kurtosis), “quant” (quantile,
used with “quant=” option), “obs” (number of observa-
tions), “nas” (number of NA values), “first” (first observa-
tion in group), “last” (last observation in group), “unique”
(single unique group value, if present), “none” (disallow
contractions).
If copying an alpha series, only the non-summary methods
“max”, “min”, “obs”, “nas”, first”, “last”, “unique” and
“none” are supported.
For copying of numeric series, the default contraction
method is “c=mean”; for copying of alpha series, the
default is “c=unique”.
quant=number Quantile value to be used when contracting using the
“c=quant” option (e.g, “quant=.3”).
nacat Treat “NA” values as a category when copying using gen-
eral match merge operations.

Most of the conversion options should be self-explanatory. As for the others: “first” and
“last” give the first and last non-missing observed for a given group ID; “obs” provides the
number of non-missing values for a given group; “nas” reports the number of NAs in the
group; “unique” will provide the value in the source series if it is the identical for all obser-
vations in the group, and will return NA otherwise; “none” will cause the copy to fail if
there are multiple observations in any group—this setting may be used if you wish to pro-
hibit all contractions.

On a match merge expansion, copying with match merging will repeat the value of the
source for every observation with matching identifier values in the destination. If both the
source and destination have multiple values for a given ID, EViews will first perform a con-
traction across IDs in the source (if not ruled out by “c=none”), and then perform the
expansion by replicating the contracted value in the destination. For example, converting
from a quarterly panel to an annual panel using match merge, EViews will first contract the
data across IDs down to a single quarterly time series, will convert the series to an annual
copy—417

frequency, then will assign the annual data to each of the cross-sections in the destination
page.

Examples
copy good_equation best_equation

makes an exact copy of GOOD_EQUATION and names it BEST_EQUATION.


copy graph_1 wf2::wkly\graph1

copies GRAPH_1 from the default page of the current workfile to GRAPH1 in the page WKLY
of the workfile WF2.
copy gdp usdat::

copies GDP from the current workfile to GDP in the USDAT database or workfile.
copy ::gdp macro1::gdp_us

copies GDP from the default database to either the open workfile MACRO1, or the database
named MACRO1 if there is no open workfile with that name. If there is an open workfile
MACRO1 you may use
copy ::gdp ::macro1::gdp_us

to specify explicitly that you wish to write to the MACRO1 database.


copy(smpl="1990 2000") page1\pop page2\ @src county @date @dest
county @date

copies POP data for 1990 through 2005 from PAGE1 to PAGE2, match merge using the ids
COUNTY and the date structure of the two pages.
copy(smpl="1990 2000", c=mean) panelpage\inc countypage\ county
county

copies the INC data from the PANELPAGE to the COUNTYPAGE, match merging using the
values of the COUNTY series, and contracting the panel data by computing means for each
county using the specified sample.
copy countypage\pop panelpage\ county county

match merges the POP data from the COUNTYPAGE to the PANELPAGE using the values of
the COUNTY series.
copy(c=x, merge) quarterly::page1\ser* annual::page6\*

copies all objects with names beginning with “SER” on page PAGE1 of workfile QUARTERLY
into page PAGE6 of workfile ANNUAL using the existing names. Series objects with data that
can be (high-to-low) frequency converted will take the maximum value within a low-fre-
quency period as the conversion method. If destination series already exist with the same
name as the source series, the data will be merged. If destination objects (non-series) exist
with the same name as source series, they will be overwritten.
418—Chapter 17.Command Reference

Note that since databases are read from disk, you may provide a path for the database in the
container specification, as in:
copy "c:\my data\dba.edb::ser01" ser02

which copies the object SER01 from the database DBA.EDB located in the path “C:\MY
DATA\” to SER02 in the default workfile page.
copy gd* "c:\my data\findat::"

makes a duplicate of all objects in the default page of the current workfile with names start-
ing with “GD” to the database FINDAT in the root of “C:\MY DATA\”.

Cross-references
See “Copying Objects” on page 342 of User’s Guide I for a discussion of copying and moving
objects.

See also fetch (p. 449), store (p. 600), and Link::linkto (p. 530) in the Object Refer-
ence.

cor Interactive Use Commands

Compute Pearson product-moment (ordinary) correlations for the specified series or


groups.

Syntax
cor(options) arg1 [arg2 arg3...]

where arg1, arg2, etc. are the names of series or groups.

Note that this command is a limited feature version of the group view Group::cor (p. 453)
in the Object Reference.

Options
wgt=name Name of series containing weights.
(optional)
wgtmethod=arg Weighting method (when weights are specified using
(default = “weight=”): frequency (“freq”), inverse of variances
“sstdev”) (“var”), inverse of standard deviation (“stdev”), scaled
inverse of variances (“svar”), scaled inverse of standard
deviations (“sstdev”).
pairwise Compute using pairwise deletion of observations with
missing cases (pairwise samples).
count—419

out=name Basename for saving output. All results will be saved in


Sym matrices named using the string “CORR”, appended to
the basename (e.g., the correlation specified by “out=my”
is saved in the Sym matrix “MYCORR”).
prompt Force the dialog to appear from within a program.
p Print the result.

Examples
cor height weight age

displays a 3  3 Pearson correlation matrix for the three series HEIGHT, WEIGHT, and AGE.

Cross-references
See Group::cor (p. 453) in the Object Reference for more general routines for computing
correlations.

See also cov (p. 421). For simple functions to perform the calculations, see @cor (p. 766),
and @cov (p. 767).

count Interactive Use Commands

Estimates models where the dependent variable is a nonnegative integer count.

Syntax
count(options) y x1 [x2 x3...]
count(options) specification

Follow the count keyword by the name of the dependent variable and a list of regressors.

Options
d=arg Likelihood specification: Poisson likelihood (“p”), normal
(default=“p”) quasi-likelihood (“n”), exponential likelihood (“e”), nega-
tive binomial likelihood or quasi-likelihood (“b”).
v=positive_num Specify fixed value for QML parameter in normal and nega-
(default=1) tive binomial quasi-likelihoods.
optmethod = arg Optimization method: “bfgs” (BFGS); “newton” (Newton-
Raphson), “opg” or “bhhh” (OPG or BHHH), “legacy”
(EViews legacy).
Newton-Raphson is the default method.
420—Chapter 17.Command Reference

optstep = arg Step method: “marquardt” (Marquardt); “dogleg” (Dog-


leg); “linesearch” (Line search).
Marquardt is the default method.
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich methods)., “glm” (GLM
method)..
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian).
(Applicable when non-legacy “optmethod=”.)
h Huber-White quasi-maximum likelihood (QML) standard
errors and covariances.
(Legacy option Applicable when “optmethod=legacy”).
g GLM standard errors and covariances.
(Legacy option Applicable when “optmethod=legacy”).
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
s Use the current coefficient values in “C” as starting values
(see also param (p. 564)).
s=number Specify a number between zero and one to determine start-
ing values as a fraction of the EViews default values (out of
range values are set to “s=1”).
prompt Force the dialog to appear from within a program.
p Print the result.

Examples
The command:
count(d=n,v=2,cov=glm) y c x1 x2

estimates a normal QML count model of Y on a constant, X1, and X2, with fixed variance
parameter 2, and GLM standard errors.
count arrest c job police
makeresid(g) res_g

estimates a Poisson count model of ARREST on a constant, JOB, and POLICE, and stores the
generalized residuals in the series RES_G.
cov—421

count(d=p) y c x1
fit yhat

estimates a Poisson count model of Y on a constant and X1, and saves the fitted values (con-
ditional mean) in the series YHAT.
count(d=p, h) y c x1

estimates the same model with QML standard errors and covariances.

Cross-references
See “Count Models” on page 1477 of User’s Guide II for additional discussion.

See Equation::count (p. 113) of the Object Reference for the equivalent equation object
command.

cov Interactive Use Commands

Compute Pearson product-moment (ordinary) covariances for the specified series or


groups.

Syntax
cor arg1 [arg2 arg3...]

where arg1, arg2, etc. are the names of series or groups.

Note that this command is a limited feature version of the group view Group::cov (p. 457)
in the Object Reference.

Options
wgt=name Name of series containing weights.
(optional)
wgtmethod=arg Weighting method (when weights are specified using
(default = “weight=”): frequency (“freq”), inverse of variances
“sstdev”) (“var”), inverse of standard deviation (“stdev”), scaled
inverse of variances (“svar”), scaled inverse of standard
deviations (“sstdev”).
pairwise Compute using pairwise deletion of observations with
missing cases (pairwise samples).
422—Chapter 17.Command Reference

out=name Basename for saving output. All results will be saved in


Sym matrices named using the string “CORR”, appended to
the basename (e.g., the correlation specified by “out=my”
is saved in the sym matrix “MYCORR”).
prompt Force the dialog to appear from within a program.
p Print the result.

Examples
cov height weight age

displays a 3  3 Pearson covariance matrix for the three series HEIGHT, WEIGHT, and AGE.

Cross-references
See Group::cov (p. 457) in the Object Reference for more general routines for computing
covariances.

See also cor (p. 418) .For simple functions to perform the calculations, see @cor (p. 766),
and @cov (p. 767).

create Object Container, Data, and File Commands

Create workfile.

This command has been replaced by wfcreate (p. 634) and pagecreate (p. 540).

cross Interactive Use Commands

Displays cross correlations (correlograms) for a pair of series.

Syntax
cross(n,options) ser1 ser2 [ser3 ...]

You must specify the number of lags n to use in computing the cross correlations as the first
option. EViews will create an untitled group from the specified series and groups, and will
display the cross correlation view for the group.

Options
The following options may be specified inside the parentheses after the number of lags:
prompt Force the dialog to appear from within a program.
p Print the cross correlogram.
data—423

Examples
cross(36) log(m1) dlog(cpi)

displays the cross correlogram between the log of M1 and the first difference of the log of
CPI, using up to 36 leads and lags.
equation eq1.arch sp500 c
eq1.makeresid(s) res_std
cross(24) res_std^2 res_std

The first line estimates a GARCH(1,1) model and the second line retrieves the standardized
residuals. The third line plots the cross correlogram squared standardized residual and the
standardized residual, up to 24 leads and lags. This correlogram provides a rough check of
asymmetry in the ARCH effect.

Cross-references
See “Cross Correlations and Correlograms” on page 706 of User’s Guide I for discussion.

See Group::cross (p. 461) of the Object Reference for the equivalent group view command.

Object Creation Commands || Object Assignment Commands || Interac-


data tive Use Commands

Enter data from keyboard.

Opens an unnamed group window to edit one or more series.

Syntax
data arg1 [arg2 arg3 ...]

Follow the data keyword by a list of series and group names. You can list existing names or
new names. Unrecognized names will cause new series to be added to the workfile. These
series will be initialized with the value “NA”.

Examples
data group1 newx newy

opens a group window containing the series in group GROUP1, and the series NEWX and
NEWY.

Cross-references
See “Entering Data” on page 153 of User’s Guide I for a discussion of the process of entering
data from the keyboard.
424—Chapter 17.Command Reference

db Object Container, Data, and File Commands

Open or create a database.

If the specified database does not exist, a new (empty) database will be created and opened.
The opened database will become the default database.

Syntax
db(options) [path\]db_name [as shorthand_name]

Follow the db command by the name of the database to be opened or to be created (if it
does not already exist). You may include a path name to work with a database not in the
default path.

You may use the “as” keyword to provide an optional shorthand_name or short text label
which may be used to refer to the database in commands and programs. If you leave this
field blank, a default shorthand_name will be assigned automatically.

See “Database Shorthands” on page 337 of User’s Guide I for additional discussion.

Options
See dbopen (p. 428) for a list of available options for working with foreign format data-
bases.

Examples
db findat

opens the database FINDAT in the default path and makes it the default database from
which to store and fetch objects. If the database FINDAT does not already exist, an empty
database named FINDAT will be created and opened.

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews databases.

See also dbcreate (p. 426) and dbopen (p. 428).

dbcopy Object Container, Data, and File Commands

Make a copy of an existing database.

Syntax
dbcopy [path\]source_name [path\]copy_name
dbcopy—425

Follow the dbcopy command by the name of the existing database and a name for the copy.
You should include a path name to copy from or to a database that is not in the default
directory. All files associated with the database will be copied.

Options
type=arg Specify the source database type: (see table below). The
default is to read an EViews 7 database.
desttype=arg, Specify the destination database type: (see table below).
t=arg The default is to create an EViews 7 database.

The following table summaries the various database formats, along with the corresponding
allowable “type=” and “desttype=” keywords:

Option Keywords
Aremos-TSD x “a”, “aremos”, “tsd”
DRIBase x “b” “dribase”
DRIPro Link x “dripro”
DRI DDS “dds”
EViews “e”, “evdb”
EViews 6 compatible “eviews6”
FAME “f”, “fame”
GiveWin/PcGive “g”, “give”
RATS 4.x “r”, “rats”
RATS Portable / TROLL “l”, “trl”
TSP Portable “t”, “tsp”

For the source specification, the following options may be required when connecting to a
remote server:
s=server_id, Server name
server=server_id
u=user, Username
username=user
p=pwd, Password
password=pwd

For the destination specification, the following options may be required when connecting to
a remote server:
426—Chapter 17.Command Reference

dests=server_id, Server name


destserver
=server_id
destu=user, Username
destusername=us
er
destp=pwd, Password
destpassword
=pwd

Examples
dbcopy usdat c:\backup\usdat

makes a copy of all files associated with the database USDAT in the default path and stores
it in the “c:\backup” directory under the basename “Usdat”.

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews databases.

See also dbrename (p. 432) and dbdelete (p. 428).

dbcreate Object Container, Data, and File Commands

Create a new database.

Syntax
dbcreate(options) [path\]db_name [as shorthand_name]

Follow the dbcreate keyword by a name for the new database. You may include a path
name to create a database not in the default directory. The new database will become the
default database.

You may use the “as” keyword to provide an optional shorthand_name or a short text label
which may be used to refer to the open database in commands and programs. If you leave
this field blank, a default shorthand_name will be assigned automatically. See “Database
Shorthands” on page 337 of the User’s Guide I for additional discussion.

Options
type=arg, t=arg Specify the database type: (see table below). The default is
to create an EViews 7 database.
dbcreate—427

The following table summaries the various database formats, along with the corresponding
“type=” keywords:

Option Keywords
Aremos-TSD x “a”, “aremos”, “tsd”
DRIBase x “b” “dribase”
DRIPro Link x “dripro”
DRI DDS “dds”
EViews “e”, “evdb”
EViews 6 compatible “eviews6”
FAME “f”, “fame”
GiveWin/PcGive “g”, “give”
RATS 4.x “r”, “rats”
RATS Portable / TROLL “l”, “trl”
TSP Portable “t”, “tsp”

DRIBase and FAME databases are not supported in EViews Standard Edition.

The following options may be required when connecting to a remote server:


s=server_id, Server name
server=server_id
u=user, Username
username=user
p=pwd, Password
password=pwd

Examples
dbcreate macrodat

creates a new database named MACRODAT in the default path, and makes it the default
database from which to store and fetch objects. This command will issue an error message if
a database named MACRODAT already exists. To open an existing database, use dbopen
(p. 428) or db (p. 424).

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews databases.

See also dbopen (p. 428) or db (p. 424).


428—Chapter 17.Command Reference

dbdelete Object Container, Data, and File Commands

Delete an existing database (all files associated with the specified database).

Syntax
dbdelete [path\]db_name

Follow the dbdelete keyword by the name of the database to be deleted. You may include
a path name to delete a database not in the default path.

Examples
dbdelete c:\temp\testdat

deletes all files associated with the TESTDAT database in the specified directory.

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews databases.

See also dbcopy (p. 424) and dbdelete (p. 428).

dbopen Object Container, Data, and File Commands

Open an existing database.

Syntax
dbopen(options) [path\]db_name [as shorthand_name]

Follow the dbopen keyword with the name of a database. You should include a path name
to open a database not in the default path. The opened database will become the default
database.

You do not need to specify a database name when opening a Datastream or FRED connec-
tion (“type=datastream” or “type=fred”) as EViews will automatically connect to the
proper location.

You may use the “as” keyword to provide an optional shorthand_name or a short text label
which is used to refer to the open database in commands and programs. If you leave this
field blank, a default shorthand_name will be assigned automatically.

See “Database Shorthands” on page 337 of User’s Guide I for additional discussion.
dbopen—429

By default, EViews will use the extension of the database file to determine type. For exam-
ple, files with the extension “.EDB” will be opened as an EViews database. You may use the
“type=” option to specify an explicit type.

Options
type=arg, t=arg Specify the database type: (see table below).

The following table summaries the various database formats, along with the corresponding
“type=” keywords:

Option “type=” keywords Notes


Australian Bureau of Statistics “abs” (b)
SDMX
Bloomberg “bloom” (a), (b)
Bureau of Economic Analysis “bea” (b)
Bureau of Labor Statistics “bls” (b)
CEIC “ceic” (a), (b)
Datastream “datastream” (a), (b)
DBnomics “dbnomics” (b)
Deutsche Bundesbank SDMX “bbk” (b)
ECB (European Central Bank) ecb” (b)
EIA Bulk File “eiabulk” (a), (c)
EIA (U.S. Energy Information “eia” (a), (b)
Administration)
Eurostat SDMX “eurostat” (b)
EViews “e”, “eviews”
FAME “f”, “fame” (a)
FRED “fred” (b)
FRED v1 “fredv1” (b)
Haver “h”, “haver” (a)
IHS Global Insight “ihs global insight” (a), (b)
IHS Magellan “magellan” (a), (b)
IHSMarkit API “ihsmarkit” (a), (b)
IMF (International Monetary “imf” (b)
Fund) SDMX
INSEE (National Institute of Statis- “insee” (b)
tics and Economic Studies) SDMX
Moody’s Economy.com “economy” (a), (b)
430—Chapter 17.Command Reference

NOAA (National Oceanic And “noaa” (b)


Atmospheric Administration)
OECD (Organization for Economic “oecd” (b)
Cooperation and Development)
SDMX
SDMX_ML “sdmx” (a), (c)
StatCan SDMX (Statistics Canada “statcan” (a), (b)
SDMX)
Trading Economics “tradingeconomics” (a), (b)
TSP Portable “t”, “tsp”
UN (United Nations) “un” (b)
US Census “uscensus” (b)
WHO (World Health Organization) “who” (a), (b)
World Bank “worldbank” (b)

• (a) Not supported in EViews Standard Edition.


• (b) You must have an active connection to the internet to access these databases.
• (c) You must have internet access to download these file-based databases prior to
opening them with EViews.

In addition, specific types may require installation of additional software. For details see,
“Notes on Particular Formats” on page 364 in User’s Guide I.

The following options may be required when connecting to a remote server:


s=server_id, Server name
server=server_id
u=user, Username
username=user
p=pwd, Password
password=pwd

Examples
dbopen c:\data\us1

opens a database named US1 in the C:\DATA directory. The command:


dbopen us1

opens a database in the default path. If the specified database does not exist, EViews will
issue an error message. You should use db (p. 424) or dbcreate (p. 426) to create a new
database.
dbrebuild—431

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews databases.

See also db (p. 424) and dbcreate (p. 426).

dbpack Object Container, Data, and File Commands

Pack an existing database.

Syntax
dbpack [path\]db_name

Follow the dbpack keyword by a database name. You may include a path name to pack a
database not in the default path.

Examples
dbpack findat

packs the database named FINDAT in the default path.

Cross-references
See “Packing the Database” on page 361 of User’s Guide I for additional discussion.

See also dbrebuild (p. 431).

dbrebuild Object Container, Data, and File Commands

Rebuild an existing database.

Rebuild a seriously damaged database into a new database file.

Syntax
dbrebuild [path\]source_name [path\]dest_name

Follow the dbrebuild keyword by the name of the database to be rebuilt, and then a new
database name.

Examples
If you issue the command:
dbrebuild testdat fixed_testdat
432—Chapter 17.Command Reference

EViews will attempt to rebuild the database TESTDAT into the database FIXED_TESTDAT in
the default directory.

Cross-references
See “Maintaining the Database” on page 360 of User’s Guide I for a discussion.

See also dbpack (p. 431).

dbrename Object Container, Data, and File Commands

Rename an existing database.

dbrename renames all files associated with the specified database.

Syntax
dbrename [path\]old_name [path\]new_name

Follow the dbrename keyword with the current name of an existing database and the new
name for the database.

Examples
dbrename testdat mydat

Renames all files associated with the TESTDAT database in the specified directory to MYDAT
in the default directory.

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews databases.

See db (p. 424) and dbcreate (p. 426). See also dbcopy (p. 424) and dbdelete (p. 428).

delete Object Utility Commands

Deletes objects from a workfile or a database.

Syntax
delete(options) arg1 [arg2 arg3 ...]

Follow the keyword by a list of the names of any objects you wish to remove from the cur-
rent workfile. Deleting does not remove objects that have been stored on disk in EViews
database files.
deleteaddin—433

Options
noerr Do not error if the object doesn’t exist.

You can delete an object from a database by prefixing the name with the database name and
a double colon. You can use a pattern to delete all objects from a workfile or database with
names that match the pattern. Use the “?” to match any one character and the “*” to match
zero or more characters.

If you use delete in a program file, EViews will delete the listed objects without prompting
you to confirm each deletion.

Examples
To delete all objects in the workfile with names beginning with “TEMP”, you may use the
command:
delete temp*

To delete the objects CONS and INVEST from the database MACRO1, use:
delete macro1::cons macro1::invest

Cross-references
See “Object Commands” on page 21 for a discussion of working with objects.

See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews databases.

deleteaddin Programming Commands

Unregister a program file as an EViews Add-in.

Syntax
deleteaddin(options) [path\]prog_name

unregisters the specified program file as an EViews Add-in.

If you do not provide the optional path specification, EViews looks for the program file in
the default EViews Add-ins directory.

Explicit path specifications containing “.\” and “..\” (to indicate the current level and one
directory level up) are evaluated relative EViews default directory.

You may use the special “<addins>” directory keyword in your path specification.
434—Chapter 17.Command Reference

Options
type=arg Specify the Add-ins type, where arg is the name of a
EViews object type. The default is to create a global Add-
in.
proc=arg User-defined command/procedure name. If omitted, the
Add-in will not have a command form.

Examples
deleteaddin .\myaddin.prg

unregisters the Add-in associated with file “Myaddin.prg”.

Alternatively,
deleteaddin(proc="myaddin")

unregisters the Add-in whose proc name matches “myaddin”. Note that this name may not
match the program name.
deleteaddin(type="graph", proc="recshade")

unregisters the graph “Recshade” specific Add-in. In cases, where more than 1 Add-in has
the same proc name, the type is useful to differentiate which is to be unregistered.

Cross-references
See Chapter 8. “Add-ins,” on page 207 for a detailed discussion of Add-ins.

did Interactive Use Commands

Estimate a equation in a panel structured workfile using the difference-in-difference esti-


mator.

Syntax
did(options) y [x1] [@ treatment]

List the dependent variable, followed by an optional list of exogenous regressors, followed
by an “@” and then the binary treatment variable. You should not include a constant in the
specification.
do—435

Options
coef=arg Specify the name of the coefficient vector. The default
behavior is to use the “C” coefficient vector.
prompt Force the dialog to appear from within a program.
p Print results.

Examples
did asmrs @ post

estimates an equation by difference-in-difference with ASMRS as the outcome variable, and


POST as the treatment variable.
did lemp lpop @ treated

estimates an equation by difference-in-difference with LEMP as the outcome variable,


TREATED as the treatment variable, and LPOP as an exogenous regressor.

Cross-references
See Chapter 56. “Difference-in-Difference Estimation,” on page 2389 for a discussion of dif-
ference-in-difference models.

do Command Actions

Execute without opening window.

Syntax
do procedure

do is most useful in EViews programs where you wish to run a series of commands without
opening windows in the workfile area.

Examples
output(t) c:\result\junk1
do gdp.adf(c, 4, p)

The first line redirects table output to a file on disk. The second line carries out a unit root
test of GDP without opening a window, and prints the results to the disk file.

Cross-references
See “Object Commands” on page 21 for a discussion of working with objects.

Chapter 1. “Object View and Procedure Reference,” on page 3 in the Object Reference pro-
vides a complete listing of the views of the various objects.
436—Chapter 17.Command Reference

See also show (p. 589).

driconvert Object Container, Data, and File Commands

Convert the entire DRI Basic Economics database into an EViews database.

You must create an EViews database to store the converted DRI data before you use this
command. This command may be very time-consuming.

Syntax
driconvert db_name

Follow the command by listing the name of an existing EViews database into which you
would like to copy the DRI data. You may include a path name to specify a database not in
the default path.

Examples
dbcreate dribasic
driconvert dribasic
driconvert c:\mydata\dridbase

The first line creates a new (empty) database named DRIBASIC in the default directory. The
second line copies all the data in the DRI Basic Economics database into in the DRIBASIC
database. The last example copies the DRI data into the database DRIDBASE that is located
in the C:\MYDATA directory.

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of the User’s Guide I for a discussion of
EViews databases.

See also dbcreate (p. 426) and db (p. 424).

enet Interactive Use Commands

Estimation of an elastic net model, including options for Lasso and ridge regression.

Syntax
enet(options) y x1 [x2 x3 ...] [@vw(...)]

List the dependent variable first, followed by a list of the independent variables. Use a “C” if
you wish to include an unpenalized intercept term.

Note that PDL and ARMA terms are not permitted in elastic net specifications.
enet—437

If you wish to specify regressors with an individual penalty weight q j , or to place inequality
restrictions on the coefficient values, you may do so using special expressions of the form:
@vw(series_name, weight_value)
or
@vw(series_name[, wgt=weight_value, cmin=coef_min, cmax=coef_max])
where weight_value is a non-negative value, coef_min is a non-positive minimum coefficient
value, and coef_max is a non-negative maximum coefficient value.

There are two forms of the special expression.

In the abbreviated form, you specify the variable name followed by the penalty weight
value.

In the more general form, you specify the variable name followed by one or more keyword
expressions in arbitrary order, with the “wgt=” argument specifying the penalty weight,
“cmin=” with a non-positive minimum coefficient value, and “cmax=” with a non-negative
maximum coefficient value.

When specifying individual regressor behavior using @vw, keep in mind that:
• The special intercept variable “C” is always non-penalized and has an implicit weight
q  0.0 .
• Individual penalty weights may be also specified using a vector in the Individual
lambda wgts. vector edit field on the Penalty dialog page (or using the command
estimation option “lambdawgt=vector_name”). If the vector weights are specified
and individual weights are specified using the @vw keyword, the vector weights will
be applied first, followed by the individual variable weights.
• Individual coefficient limit values may also be specified using vectors in the Min val-
ues vector and Max values vector edit fields on the Options dialog page (or the com-
mand estimation options “coefmin=vector_name” and “coefmax=vector_name”). If
vector coefficient limits are specified and individual regressor limits are specified
using the @vw keyword, the vector limits will be applied first, followed by the individ-
ual limits weights.

EViews will normalize the individual penalty weights so that they sum to the number of
coefficients.
438—Chapter 17.Command Reference

Options
Specification Options
penalty=arg Type of threshold estimation: “enet” (elastic net),
(default=“el”) “ridge” (ridge), “lasso” (Lasso).
alpha=arg Value of the mixing parameter. Must be a value from
(default=“.5”) zero to one.
lambda=arg Value(s) of the penalty parameter. Can be one or more
numbers or vector objects.Values must be zero or
greater.
If left blank (default) EViews will generate a list.

Penalty Options
ytrans=arg Scaling of the dependent variable: “none” (none), “L1”
(default=“none”) (L1), “L2” (L2), “stdsmpl” (sample standard deviation),
“stdpop” (population standard deviation), “minmax”
(min-max).
xtrans=arg Scaling of the regressor variables: “none” (none), “L1”
(default=“stdpop”) (L1 norm), “L2” (L2 norm), “stdsmpl” (sample standard
deviation), “stdpop” (population standard deviation),
“minmax” (min-max).
nlambdas=integer Number of penalty values for EViews-supplied list.
(default=100)
lambdaratio=arg Ratio of minimum to maximum lambda for EViews-sup-
plied list.
You may specify a value for the ratio parameter, or you
may leave the edit field blank to let EViews specify a
default value based on the number of observations T
and the number of potential regressors p .
By default, EViews will set the ratio to 0.001.
lambdawgt= Vector of individual penalty weights, containing non-
vector_name negative values sized to and matching the order of the
variables in the specification.
If a vector is provided and individual weights are speci-
fied using one or more @vw regressors, the vector
weights will be applied first, then overwritten by the
individual variable weights.
For comparability purposes, we normalize the final
weights so that they sum to p where p the number
of non-zero q j .
nlambdamin=integer Minimum number of lambda values in the path before
(default=5) applying stopping rules.
enet—439

minddev=arg Minimum change in deviance fraction to continue esti-


(default=1e-05) mation. Truncate path estimation if relative change in
deviance is smaller than this value.
maxedev=arg Maximum of deviance explained fraction attained to ter-
(default=0.99) minate estimation. Truncate path estimation if fraction
of null deviance explained is larger than this value.
maxvars=arg Maximum number of regressors in the model. Truncate
path estimation if the number of coefficients (including
those for non-penalized variables like the intercept)
reaches this value.
maxvarsratio=arg Maximum number of regressors in the model as a frac-
tion of the number of observations. Truncate path esti-
mation if the number of coefficients (including those for
non-penalized variables like the intercept) divided by
the number of observations reaches this value.

Cross Validation Options


cvmethod=arg Cross-validation method: “kfold” (k-fold), “simple”
(default=“kfold_cv”) (simple split), “mcarlo” (Monte Carlo), “leavepout”
(leave-P-out), “leave1out” (leave-1-out), “rolling” (roll-
ing window), “expanding” (expanding window).
cvmeasure=arg Cross-validation fit measure: “mse” (mean-squared
(default=“mse”) error), “r2” (R-squared), “mae” (mean absolute error),
“mape” (mean absolute percentage error), “smape”
(symmetric mean absolute percentage error).
cvnfolds=arg Number of folds for K-fold cross-validation.
(default=5) For “cvmethod=kfold”.
cvftrain=arg Proportion of data for split and Monte Carlo methods.
(default=0.8) For “cvmethod=simple” and “cvmethod=mcarlo”.
cvnreps=arg Number of Monte Carlo method repetitions.
(default=1) For “cvmethod=mcarlo”.
cvleaveout=arg Number of data points left out for leave-p-out method.
(default=2) For “cvmethod=leavepout”.
cvnwindows=arg Number of windows for rolling window cross-validation
(default=4) method.
For “cvmethod=rolling”.
cvinitial=arg Number of initial data points in the training set for
(default=12) expanding cross-validation.
For “cvmethod=expanding”.
440—Chapter 17.Command Reference

cvpregap=arg Number of observations between end of training set and


(default=0) beginning of test set.
For “cvmethod=simple”, “cvmethod=rolling” and
“cvmethod=expanding”.
cvhorizon=arg Number of observation in the test set.
(default=1) For “cvmethod=rolling” and “cvmethod=expanding”.
cvpostgap=arg Number of observations between end of test set and
(default=0) beginning of next training set for rolling window or
between end of test set and end of next training set for
expanding window.
For “cvmethod=rolling” and “cvmethod=expanding”

Random Number Options


seed=positive_inte- Seed the random number generator.
ger from 0 to If not specified, EViews will seed random number gener-
2,147,483,647 ator with a single integer draw from the default global
random number generator.
rnd=arg Type of random number generator: improved Knuth gen-
(default=“kn” or erator (“kn”), improved Mersenne Twister (“mt”),
method previously set Knuth’s (1997) lagged Fibonacci generator used in
using rndseed EViews 4 (“kn4”) L’Ecuyer’s (1999) combined multiple
(p. 577)). recursive generator (“le”), Matsumoto and Nishimura’s
(1998) Mersenne Twister used in EViews 4 (“mt4”).

Other Options
coefmin= Vector of individual coefficient minimum values, con-
vector_name, number taining negative or missing values sized to and matching
the order of the variables in the specification, or a nega-
tive value for the minimum for all coefficients.
Missing values in the vector should be used to indicate
that the coefficient is unrestricted.
If a vector of values is provided and individual mini-
mums are specified using one or more @vw regressors,
the vector values will be applied first, then overwritten
by the individual values.
enet—441

coefmax= Vector of individual coefficient maximum values, con-


vector_name, number taining positive or missing values sized to and matching
the order of the variables in the specification, or a posi-
tive value for the maximum for all coefficients.
Missing values in the vector should be used to indicate
that the coefficient is unrestricted.
If a vector of values is provided and individual maxi-
mums are specified using one or more @vw regressors,
the vector values will be applied first, then overwritten
by the individual values.
maxit=integer Maximum number of iterations.
conv=scalar Set convergence criterion. The criterion is based upon
the maximum of the percentage changes in the scaled
estimates. The criterion will be set to the nearest value
between 1e-24 and 0.2.
w=arg Weight series or expression.
wtype=arg Weight specification type: inverse standard deviation
(default=“istdev”) (“istdev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
showopts / -showopts [Do / do not] display estimation options in the output.
prompt Force the dialog to appear from within a program.
p Print basic results view after estimation.

Examples
The command
enet(xtrans=none, lambdaratio=.0001, cvseed=513255899) lpsa c
lcavol lweight age lbph svi lcp gleason pgg45

estimates an elastic net model with a equal to the default of 0.9, no regressor or dependent
variable scaling, automatically determined 100-element lambda path with minimum lambda
of 0.0001 times the maximum value, using the default K-fold cross-validation with 5 folds
with an MSE objective and a random generator seed of 513255899 to determine the optimal
value.

Similarly,
enet(penalty=lasso, lambdaratio=.0001, cvseed=513255899) lpsa c
lcavol lweight age lbph svi lcp gleason pgg45
442—Chapter 17.Command Reference

estimates a Lasso model with regressor population standard deviation scaling, with the
remaining settings as before, while
enet(penalty=ridge, lambdaratio=.0001, cvseed=513255899) lpsa c
lcavol lweight age lbph svi lcp gleason pgg45

estimates the equivalent ridge regression specification.

The command
enet(alpha=0.75, lambdaratio=.0001, cvmethod=rolling,
cvmeasure=smape) lpsa c lcavol lweight age_s lbph svi lcp
gleason pgg45

estimates an elastic net model with a equal to the 0.75 using rolling window cross-valida-
tion and SMAPE cross-validation.

We may use the @vw specifications to assign individual penalties and coefficient restrictions
enet(alpha=0.75, lambdaratio=.0001, cvmethod=rolling,
cvseed=513255899) lpsa c @vw(lcavol, cmax=.4) lweight age lbph
svi lcp gleason @vw(pgg45, cmax=0.075, w=1.2)

estimates an elastic net model with the coefficient of LCAVOL restricted to be less than or
equal to 0.4, and the coefficient of PGG45 having a relative penalty weight of 1.2, and a
maximum value of 0.075.

Identical specifications may be estimated using vectors of penalty weights and coefficient
restrictions,
vector(9) cmax = na
cmax(2) = 0.4
cmax(9) = 1.2
vector(9) lwgt = 1
lwgt(9) = 1.2
enet(alpha=0.75, coefmax=cmax, lambdawgt=lwgt, lambdaratio=.0001,
cvmethod=rolling, cvseed=513255899) lpsa c lcavol lweight age
lbph svi lcp gleason pgg45

and
vector(9) cmax = na
cmax(2) = 0.4
vector(9) lwgt = 1
lwgt(9) = 50
enet(alpha=0.75, coefmax=cmax, lambdawgt=lwgt, lambdaratio=.0001,
cvmethod=rolling, cvseed=513255899) lpsa c lcavol lweight age
lbph svi lcp gleason @vw(pgg45, cmax=0.075, w=1.2)
deleteaddin—443

since the penalty weight for PGG45 in the vector is overwritten by the individual weight
specified using the @vw.

Note that in neither case is the intercept penalized, even though the corresponding element
of LWGT is equal to 1 since the specification of “C” is always implicitly treated as “@VW(C,
0)”.

Cross-references
See Chapter 37. “Elastic Net and Lasso,” on page 1603 of User’s Guide II for a discussion of
elastic net, ridge regression, and Lasso models.

See Equation::enet (p. 126) for the object version of this command.

deleteaddin Programming Commands

Unregister a program file as an EViews Add-in.

Syntax
deleteaddin(options) [path\]prog_name

unregisters the specified program file as an EViews Add-in.

If you do not provide the optional path specification, EViews looks for the program file in
the default EViews Add-ins directory.

Explicit path specifications containing “.\” and “..\” (to indicate the current level and one
directory level up) are evaluated relative EViews default directory.

You may use the special “<addins>” directory keyword in your path specification.

Options
type=arg Specify the Add-ins type, where arg is the name of a
EViews object type. The default is to create a global Add-
in.
proc=arg User-defined command/procedure name. If omitted, the
Add-in will not have a command form.

Examples
deleteaddin .\myaddin.prg

unregisters the Add-in associated with file “Myaddin.prg”.

Alternatively,
deleteaddin(proc="myaddin")
444—Chapter 17.Command Reference

unregisters the Add-in whose proc name matches “myaddin”. Note that this name may not
match the program name.
deleteaddin(type="graph", proc="recshade")

unregisters the graph “Recshade” specific Add-in. In cases, where more than 1 Add-in has
the same proc name, the type is useful to differentiate which is to be unregistered.

Cross-references
See Chapter 8. “Add-ins,” on page 207 for a detailed discussion of Add-ins.

exec Programming Commands

Execute a program.

The exec command executes a program. The program may be located in memory or stored
in a program file on disk.

Syntax
exec(options) [path\]prog_name(prog_options) [%0 %1 …]

If you wish to pass one or more options to the program, you should enclose them in paren-
theses immediately after the filename. If the program has arguments, you should list them
after the filename.

EViews first checks to see if the specified program is in memory. If the program is not
located, EViews then looks for the program on disk in the EViews Add-ins directory, or in the
specified path. The program file should have a “.PRG” extension, which you need not spec-
ify in the prog_name.
exec—445

Options
integer Set maximum errors allowed before halting the program in
(default=1) interactive mode.
Note that the integer option does not apply when using
exec in a program, it only applies when using exec from the
command line. When using exec in a parent program to
execute a child program, the child program inherits the
maximum error count from the parent.
c Run program file without opening a window for display of
the program file.
verbose / quiet Verbose mode in which messages will be sent to the status
line at the bottom of the EViews window (slower execu-
tion), or quiet mode which suppresses workfile display
updates (faster execution).
v/q Same as [verbose / quiet].
ver4 / ver5 Execute program in [version 4 / version 5] compatibility
mode.
this=object_name Set the _this object for the executed program. If omitted,
the executed program will inherit the _this object from
the parent program, or from the current active workfile
object when the exec command is issued from the com-
mand window.

Examples
exec rollreg

will run the program “Rollreg.prg” in the EViews add-in directory.


exec(this=graph01) recshade

will run the program “Recshade” in the EViews add-in directory, setting the _this object to
GRAPH01.
exec(4) c:\myfiles\simul.prg(h=3) xhat

will run the program “Simul.prg” in the path “c:\myfiles\”, with program option string
“h=3”, the %0 argument set to “XHAT”, and with the maximum error count set to 4.

Note that in contrast to the run command, exec will not stop executing a running program
after returning from the executed program. For example if you have a program containing:
exec simul
print x
446—Chapter 17.Command Reference

the print statement will be executed after running the “Simul.prg” program. If you replace
exec with run, the program will stop after executing the commands in “Simul.prg”.

Cross-references
See “Executing a Program” on page 133 of User’s Guide I and “The Active Object Keyword”
on page 230 in the Command and Programming Reference for further details.

See also run (p. 581) and include (p. 349).

exit Global Commands

Exit from EViews (close the EViews application).

You will be prompted to save objects and workfiles which have changed since the last time
they were saved to disk. Be sure to save your workfiles, if desired, since all changes that you
do not save to a disk file will be lost.

Syntax
exit

Cross-references
See also close (p. 393) and save (p. 583).

expand Object Container, Data, and File Commands

Expand a workfile.

No longer supported. See the replacement command pagestruct (p. 558).

facbreak Interactive Use Commands

Factor breakpoint test for stability.

Carries out a factor breakpoint test for parameter constancy.

Syntax
facbreak(options) ser1 [ser2 ser3 ...] @ x1 x2 x3

You must provide one or more series to be used as the factors with which to split the sample
into categories. To specify more than one factor, separate the factors by a space. If the equa-
tion is specified by list and contains no linear terms, you may specify a subset of the regres-
sors to be tested for a breakpoint after an “@” sign.
factest—447

Options
p Print the result of the test.

Examples
The commands
ls log(spot) c log(p_us) log(p_uk)
facbreak season

perform a regression of the log of SPOT on a constant, the log of P_US, and the log of P_UK,
and employ a factor breakpoint test to determine whether the parameters are stable through
the different values of SEASON.

To test whether only the constant term and the coefficient on the log of P_US are “stable”
enter the commands:
facbreak season @ c log(p_us)

Cross-references
See “Factor Breakpoint Test” on page 1225 of User’s Guide II for further discussion.

See also Equation::facbreak (p. 133) and Equation::rls (p. 233) in the Object Refer-
ence.

factest Interactive Use Commands

Specify and estimate a factor analysis model.

Syntax
factest(method=arg, options) x1 [x2 x3...] [@partial z1 z2 z3...]
factest(method=arg, options) matrix_name [[obs] [conditioning]] [@ name1 name2
name3...]

where:
method=arg Factor estimation method: “ml” (maximum likelihood),
(default= “ml”) “gls” (generalized least squares), “ipf” (iterated principal
factors), “pace” (non-iterative partitioned covariance
matrix estimation), “pf” (principal factors), “uls”
(unweighted least squares)

and the available options are specific to the factor estimation method (see “Factor Methods”
on page 273 of the Object Reference).
448—Chapter 17.Command Reference

The factest command allows you to estimated a factor analysis model without first declar-
ing a factor object and then applying an estimation method. It provides a convenient
method of interactively estimating transitory specifications that are not to be named and
saved with the workfile.

Estimation of a factor analysis specification using factest only differs from estimation
using a named factor and a factor estimation procedure (e.g., Factor::ipf (p. 290) in the
Object Reference) in the use of the “method=” option and in the fact that the command
results in an unnamed factor object.

Examples
The command:
factest(method=gls) g1

estimates a factor analysis model for the series in G1 using GLS. The result is an unnamed
factor object. (Almost) equivalently, we may declaring and estimate the factor analysis
object using the Factor::gls estimation method procedure
factor f1.gls g1

which differs only in the fact that the former yields an unnamed factor object and the latter
saves the object F1 in the workfile.

The command:
factest(method=ml) group01 @partial ser1 ser2

estimates the factor model using the partial correlation for the series in GROUP01, condi-
tional on the series SER1 and SER2. The command is equivalent to:
factor f2.ml group01 @partial ser1 ser2

except the latter names the factor object F2.

Cross-references
See Chapter 60. “Factor Analysis,” on page 2491 of User’s Guide II for a general discussion of
factor analysis. The various estimation methods are described in “Estimation Methods” on
page 2527 of User’s Guide II.

See Factor::gls (p. 285), Factor::ipf (p. 290), Factor::ml (p. 299), Factor::pf
(p. 311), and Factor::uls (p. 326) all in the Object Reference.
fetch—449

fetch Object Container, Data, and File Commands

Fetch objects from databases or databank files into the workfile.

fetch reads one or more objects from EViews databases or databank files into the active
workfile. The objects are loaded into the workfile using the object in the database or using
the databank file name.

If you fetch a series into a workfile with a different frequency, EViews will automatically
apply the frequency conversion method attached to the series by setconvert. If the series
does not have an attached conversion method, EViews will use the method set by
Options/Date-Frequency in the main menu. You can override the conversion method by
specifying an explicit conversion method option.

Syntax
fetch(options) object_list

The fetch command keyword is followed by a list of object names separated by spaces. The
default behavior is to fetch the objects from the default database (this is a change from ver-
sions of EViews prior to EViews 3.x where the default was to fetch from individual databank
files).

You can precede the object name with a database name and the double colon “::” to indicate
a specific database source. If you specify the database name as an option in parentheses (see
below), all objects without an explicit database prefix will be fetched from the specified
database. You may optionally fetch from individual databank files or search among regis-
tered databases.

You may use wild card characters, “?” (to match a single character) or “*” (to match zero or
more characters), in the object name list. All objects with names matching the pattern will
be fetched.

To fetch from individual databank files that are not in the default path, you should include
an explicit path. If you have more than one object with the same file name (for example, an
equation and a series named CONS), then you should supply the full object file name
including identifying extensions.

Options
d=db_name Fetch from specified database.
d Fetch all registered databases in registry order.
i Fetch from individual databank files.
450—Chapter 17.Command Reference

link Fetch as a database link.


notifyillegal When in a program, report illegal EViews object names. By
default, objects with illegal names are automatically
renamed. (Has no effect in the command window.)
p=prefix Specify a naming prefix that will be prepended to the listed
names to be fetched.
s=suffix Specify a naming suffix that will be appended to the listed
names to be fetched.
pi=prefix Specify a naming prefix that will be removed from the
name of the source objects once fetched into the workfile.
si=suffix Specify a naming suffix that will be removed from the
name of the source objects once fetched into the workfile.
tr=integer Truncate long series names to integer characters. The
default value of integer is 24.

The following options are available for fetch of group objects:


g=arg Group fetch options: “b” (fetch both group definition and
series), “d” (fetch only the series in the group), “l” (fetch
only the group definition).

The database specified by the double colon “::” takes precedence over the database specified
by the “d=” option.

The following options control the frequency conversion method when copying series and
group objects into a workfile page and converting from low to high frequency:
c=arg Low to high conversion methods: “r” or “repeata” (con-
stant match average), “d” or “repeats” (constant match
sum), “q” or “quada” (quadratic match average), “t” or
“quads” (quadratic match sum), “linearf” (linear match
first), “i” or “linearl” (linear match last), “cubicf” (cubic
match first), “c” or “cubicl” (cubic match last), “pointf”
(point first), “pointl” (point last).

The following options control the frequency conversion method when copying series and
group objects to a workfile, converting from high to low frequency:
fetch—451

c=arg High to low conversion methods removing NAs: “a” (aver-


age of the nonmissing observations), “s” (sum of the non-
missing observations), “f” (first nonmissing observation),
“l” (last nonmissing observation), “x” (maximum nonmiss-
ing observation), “m” (minimum nonmissing observation).
High to low conversion methods propagating NAs: “an” or
“na” (average, propagating missings), “sn” or “ns” (sum,
propagating missings), “fn” or “nf” (first, propagating
missings), “ln” or “nl” (last, propagating missings), “xn”
or “nx” (maximum, propagating missings), “mn” or “nm”
(minimum, propagating missings).

If no conversion method is specified, the series-specific or global default conversion method


will be employed.

Examples
To fetch M1, GDP, and UNEMP from the default database, use:
fetch m1 gdp unemp

To fetch M1 and GDP from the US1 database and UNEMP from the MACRO database, use
the command:
fetch(d=us1) m1 gdp macro::unemp

You can fetch all objects with names starting with “SP” by searching all registered databases
in the search order. The “c=f” option uses the first (nonmissing) observation to convert the
frequency of any matching series with a higher frequency than the destination workfile fre-
quency:
fetch(d,c=f) sp*

You can fetch M1 and UNEMP from individual databank files using:
fetch(i) m1 c:\data\unemp

To fetch all objects with names starting with “CONS” from the two databases USDAT and
UKDAT, use the command:
fetch usdat::cons* ukdat::cons*

The command:
fetch a?income

will fetch all series beginning with the letter “A”, followed by any single character, and end-
ing with the string “income”.
452—Chapter 17.Command Reference

Use the “notifyillegal” option to display a dialog when fetching the series MYIL-
LEG@LNAME that will suggest a valid name and give you to opportunity to name the object
before it is inserted into a workfile:
fetch(notifyillegal) myilleg@lname

The command:
fetch(p=us_) gdp inv cons

Fetches the series US_GDP, US_INV and US_CONS into workfile series with the same names.
fetch(si=” us equity”) ibm msft

Fetches the database series IBM US EQUITY, and MSFT US EQUITY into workfile series with
names IBM and MSFT.

Specifying the “tr” option causes EViews 10 to truncate long series names to 24 characters
(by default) instead of 300. This will let programs written for EViews 9 continue to work
with EViews 10:
fetch(d=eia, link, tr) coal.average_employees.al-tot.a

The “tr” option can also be set to a number between 0 and 300:
fetch(d=eia, link, tr=20) coal.average_employees.al-tot.a

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of data-
bases, databank files, and frequency conversion. Appendix A. “Wildcards,” on page 1227
describes the use of wildcard characters.

See also store (p. 600), and copy (p. 411).

See Series::setconvert (p. 834) in the Object Reference for information on default con-
version settings.

fit Interactive Use Commands

Computes static forecasts or fitted values from an estimated equation.

When the regressor contains lagged dependent values or ARMA terms, fit uses the actual
values of the dependent variable instead of the lagged fitted values. You may instruct fit to
compare the forecasted data to actual data, and to compute forecast summary statistics.

(Note that we recommend that you instead use the equation proc Equation::fit since it
explicitly specifies the equation of interest.)
fit—453

Not available for equations estimated using ordered methods; use Equation::makemodel
to create a model using the ordered equation results.

Syntax
fit(options) yhat [y_se]

Following the fit keyword, you should type a name for the forecast series and, optionally, a
name for the series containing the standard errors and, for ARCH specifications, a name for
the conditional variance series.

Forecast standard errors are currently not available for binary, censored, and count models.
Basic Options

d In models with implicit dependent variables, forecast the


entire expression rather than the normalized variable.
u Substitute expressions for all auto-updating series in the
equation.
g Graph the fitted values together with the ±2 standard error
bands.
ga Graph the forecasts along with the actuals (if available).
e Produce the forecast evaluation table.
i Compute the fitted values of the index. Only for binary,
censored and count models.
s Ignore ARMA terms and use only the structural part of the
equation to compute the fitted values.
n Ignore coef uncertainty in standard error calculations that
use them.
forcsmpl = Fit sample (optional). If forecast sample is not provided,
smpl the workfile sample will be employed.
f = arg Out-of-fit-sample fill behavior: “actual” (fill observations
(default= outside the fit sample with actual values for the fitted vari-
“actual”) able), “na” (fill observations outside the fit sample with
missing values).
prompt Force the dialog to appear from within a program.
p Print view.

Stochastic Options
Options for forecasting from a functional coefficients estimated equation.
454—Chapter 17.Command Reference

stochastic = arg Stochastic method: “none” (none), “mca” (Monte Carlo –


(default = asymptotic), “mcbs” (Monte Carlo – bootstrap), “bs”
“none”) (bootstrap).
reps = integer Number of stochastic replications
(default = 999)
lhr = arg Lower historical range (number between 0 and upper his-
(default = 0.1) torical range).
uhr = arg Upper historical range (number between lower historical
(default = 0.9) range and 1).
bsdep Bootstrap only the dependent variable (not the functional
coefficient variable).

Examples
equation eq1.ls cons c cons(-1) inc inc(-1)
fit c_hat c_se
genr c_up=c_hat+2*c_se
genr c_low=c_hat-2*c_se
line cons c_up c_low

The first line estimates a linear regression of CONS on a constant, CONS lagged once, INC,
and INC lagged once. The second line stores the static forecasts and their standard errors as
C_HAT and C_SE. The third and fourth lines compute the +/- 2 standard error bounds. The
fifth line plots the actual series together with the error bounds.
equation eq2.binary(d=l) y c wage edu
fit yf
fit(i) xbeta
genr yhat = 1-@clogit(-xbeta)

The first line estimates a logit specification for Y with a conditional mean that depends on a
constant, WAGE, and EDU. The second line computes the fitted probabilities, and the third
line computes the fitted values of the index. The fourth line computes the probabilities from
the fitted index using the cumulative distribution function of the logistic distribution. Note
that YF and YHAT should be identical.

Note that you cannot fit values from an ordered model. You must instead solve the values
from a model. The following lines generate fitted probabilities from an ordered model:
equation eq3.ordered y c x z
eq3.makemodel(oprob1)
solve oprob1
forecast—455

The first line estimates an ordered probit of Y on a constant, X, and Z. The second line
makes a model from the estimated equation with a name OPROB1. The third line solves the
model and computes the fitted probabilities that each observation falls in each category.

Cross-references
To perform dynamic forecasting, use forecast (p. 455).

See Chapter 25. “Forecasting from an Equation,” on page 1175 of User’s Guide II for a discus-
sion of forecasting in EViews and Chapter 31. “Discrete and Limited Dependent Variable
Models,” on page 1431 of User’s Guide II for forecasting from binary, censored, truncated,
and count models.

See “Forecasting” on page 2160 of User’s Guide II for a discussion of forecasting from sspace
models.

See Equation::forecast (p. 139) and Equation::fit (p. 134) in the Object Reference
for the equivalent object commands.

See Equation::makemodel (p. 196) and Model::solve (p. 642) in the Object Reference
for forecasting from systems of equations or ordered equations.

forecast Interactive Use Commands

Computes dynamic forecasts of the default equation.

forecast computes the forecast using the default equation for all observations in a speci-
fied sample. In some settings, you may instruct forecast to compare the forecasted data to
actual data, and to compute summary statistics.

(Note that we recommend that you instead use the equation proc Equation::forecast
since it explicitly specifies the equation of interest.)

Syntax
forecast(options) yhat [y_se]

You should enter a name for the forecast series and, optionally, a name for the series con-
taining the standard errors. Forecast standard errors are currently not available for binary or
censored models. forecast is not available for models estimated using ordered methods.
456—Chapter 17.Command Reference

Options
d In models with implicit dependent variables, forecast the
entire expression rather than the normalized variable.
u Substitute expressions for all auto-updating series in the
equation.
g Graph the forecasts together with the ±2 standard error
bands.
e Produce the forecast evaluation table.
i Compute the forecasts of the index. Only for binary, cen-
sored and count models.
s Ignore ARMA terms and use only the structural part of the
equation to compute the forecasts.
n Ignore coef uncertainty in standard error calculations that
use them.
b =arg MA backcast method: “fa” (forecast available). Only for
equations estimated with MA terms. This option is ignored
if you specify the “s” (structural forecast) option.
The default method uses the estimation sample.
f = arg Out-of-forecast-sample fill behavior: “actual” (fill observa-
(default= tions outside the forecast sample with actual values for the
“actual”) fitted variable), “na” (fill observations outside the forecast
sample with missing values).
stochastic Perform stochastic simulation for dynamic equations esti-
mated using least squares.
streps=integer Number of stochastic repetitions (for threshold regression
(default=1000) or stochastic simulation).
stfrac=number Fraction of failed repetitions before stopping (for threshold
(default=.02) regression or stochastic simulation).
prompt Force the dialog to appear from within a program.
p Print view.

Examples
The following lines:
smpl 1970q1 1990q4
equation eq1.ls con c con(-1) inc
smpl 1991q1 1995q4
forecast con_d
freeze—457

plot con_d

estimate a linear regression over the period 1970Q1–1990Q4, computes dynamic forecasts
for the period 1991Q1–1995Q4, and plots the forecast as a line graph.
equation eq1.ls m1 gdp ar(1) ma(1)
forecast m1_bj bj_se
forecast(s) m1_s s_se
plot bj_se s_se

estimates an ARMA(1,1) model, computes the forecasts and standard errors with and with-
out the ARMA terms, and plots the two forecast standard errors.

Cross-references
To perform static forecasting, see fit (p. 452).

See Chapter 25. “Forecasting from an Equation,” on page 1175 of User’s Guide II for a discus-
sion of forecasting in EViews and Chapter 31. “Discrete and Limited Dependent Variable
Models,” on page 1431 of User’s Guide II for forecasting from binary, censored, truncated,
and count models.

See “Forecasting” on page 2160 of User’s Guide II for a discussion of forecasting from sspace
models.

See Equation::forecast (p. 139) and Equation::fit (p. 134) in the Object Reference,
for the equivalent object commands.

See Equation::makemodel (p. 196) and Model::solve (p. 642) in the Object Reference
for forecasting from systems of equations or ordered equations.

freeze Command Actions

Creates graph, table, or text objects from a view.

Syntax
freeze(options, name) object_name.view_command

If you follow the keyword freeze with an object name but no view of the object, freeze
will use the default view for the object. You may provide a destination name for the object
containing the frozen view in parentheses.

Options
mode = overwrite Overwrites the object name if it already exists.
458—Chapter 17.Command Reference

Examples
freeze gdp.uroot(4,t)

creates an untitled table that contains the results of the unit root test of the series GDP.
group rates tb1 tb3 tb6
freeze(gra1) rates.line(m)
show gra1.align(2,1,1)

freezes a graph named GRA1 that contains multiple line graphs of the series in the group
RATES, realigns the individual graphs, and displays the resulting graph.
freeze(mygra) gra1 gra3 gra4
show mygra.align(2,1,1)

creates a graph object named MYGRA that combines three graph objects GRA1, GRA2, and
GRA3, and displays MYGRA in two columns.
freeze(mode=overwrite, mygra) gra1 gra2 gra3
show mygra.align(2,1,1)

creates a graph object MYGRA that combines the three graph objects GRA1, GRA2 and
GRA3, and displays MYGRA in two columns. If the object MYGRA already exists, it would
be replaced by the new object.

Cross-references
See “Object Commands” on page 21 for discussion. See also Chapter 4. “Object Basics,” on
page 107 of User’s Guide I for further discussion of objects and views of objects.

Freezing graph views is described in “Creating Graph Objects” on page 867 of User’s Guide I.

frml Object Creation Commands || Object Assignment Commands

Declare a series object with a formula for auto-updating, or specify a formula for an exist-
ing series.

Syntax
frml series_name = series_expression
frml series_name = @clear

Follow the frml keyword with a name for the object, and an assignment statement. The
special keyword “@CLEAR” is used to return the auto-updating series to an ordinary
numeric or alpha series.
frml—459

Examples
To define an auto-updating numeric or alpha series, you must use the frml keyword prior to
entering an assignment statement. The following example creates a series named LOW that
uses a formula to compute its values.:
frml low = inc<=5000 or edu<13

The auto-updating series takes the value 1 if either INC is less than or equal to 5000 or EDU
is less than 13, and 0 otherwise, and will be re-evaluated whenever INC or EDU change.

If FIRST_NAME and LAST_NAME are alpha series, then the formula declaration:
frml full_name = first_name + " " + last_name

creates an auto-updating alpha series FULL_NAME.

You may apply a frml to an existing series. The commands:


series z = 3
frml z =(x+y)/2

makes the previously created series Z an auto-updating series containing the average of
series X and Y. Note that once a series is defined to be auto-updating, it may not be modified
directly. Here, you may not edit Z, nor may you generate values into the series.

Note that the commands:


series z = 3
z = (x+y)/2

while similar, produce quite different results, since the absence of the frml keyword in the
second example means that EViews will generate fixed values in the series instead of defin-
ing a formula to compute the series values. In this latter case, the values in the series Z are
fixed, and may be modified.

One particularly useful feature of auto-updating series is the ability to reference series in
databases. The command:
frml gdp = usdata::gdp

creates a series called GDP that obtains its values from the series GDP in the database
USDATA. Similarly:
frml lgdp = log(usdata::gdp)

creates an auto-updating series that is the log of the values of GDP in the database USDATA.

To turn off auto-updating for a series or alpha, you should use the special expression
“@CLEAR” in your frml assignment. The command:
frml z = @clear
460—Chapter 17.Command Reference

sets the series to numeric or alpha value format, freezing the contents of the series at the
current values.

Cross-references
See “Auto-Updating Series” on page 219 of User’s Guide I for a discussion of updating series.

See also Link::link (p. 530) in the Object Reference.

funcoef Interactive Use Commands

Estimate a functional coefficient regression equation.

Syntax
funcoef(options) y x1 [x2 x3 ...] @ funcoef_series

List the funcoef keyword, the dependent variable and a list of the regressor variables, fol-
lowed by the “@” symbol and the name of the functional coefficient series.

Options
Basic Options

kern=arg Kernel type: “epan” (Epanechnikov, default), “trngl” (Tri-


(default=“epan”) angular), “unif” (Uniform), “gauss” (Normal–Gaussian),
“bi” (Biweight–Quartic), “tri” (Triweight).
eval=arg Evalution points: observed data (“data”), grid of values
(default=“data”) (“grid”).
if “eval=grid” you must specify the grid values using
“gmin=”, “gmax=” and “glen=”, or using “gvec=”.
gmin = arg Estimation grid minimum (if “eval=grid”). Must be speci-
fied along with “gmax=” and “glen=”.
gmax = arg Estimation grid maximum (if “eval=grid”). Must be speci-
fied along with “gmin=” and “glen=”.
glen = arg Estimation grid length (if “eval=grid”). Must be specified
along with “gmin=” and “gmax=”.
gvec = arg Estimation grid points in a vector object (if “eval=grid”).
plyk = arg Estimation polynomial degree for final stage.
(default = 1)
auxk = arg Estimation polynomial degree for pilot stage in excess of
(default = 2) final stage.
p Print results.
funcoef—461

Pilot Bandwidth Options

plth =arg Pilot bandwidth method: simple rule-of-thumb (“rot”),


(default = “rsc”) robust rule-of-thumb (“rotr”), residual squares criterion
(“rsc”), modified multi cross-validation (“cv”), user-
defined (“user”).
pltbw=arg User-defined bandwidth (if “plth=user”).
(default =1)
plthmin=arg Bandwidth grid search minimum value (if not
(default = 0.1) “plth=user”).
plthmax=arg Bandwidth grid search maximum value (if not
(default =1) “plth=user”).
plthlen=integer Bandwidth grid search length (if not “plth=user”).
(default = 100)
plthinc=integer Bandwidth grid search increment step percentage increase
(default = 10) (if not “plth=user”).
plthcup=integer Stop rule: consecutive increases of objective function
(default = 10) before stop (not available when “plth=user”).
pltm=arg Modified multifold CV m-value: percentage of sample size
(default = 10) used in bandwidth determination (when “plth=cv”).
pltq=integer Modified multifold CV Q-value: percentage of sample size
(default = 4) used in bandwidth determination (when “plth=cv”).

Final Bandwidth Options

fnlh =arg Final bandwidth method: simple rule-of-thumb (“rot”),


(default = “cv”) robust rule-of-thumb (“rotr”), residual squares criterion
(“rsc”), modified multi cross-validation (“cv”), integrated
asymptotic mean square error (“mse”), leave-one-out
cross-validation (“loo”), nonparametric AIC (“aic”), user-
defined (“user”).
fnlbw=arg User-defined bandwidth (if “fnlh=user”).
fnlhmin=arg Bandwidth grid search minimum value (if not
(default = 0.1) “fnlh=user”).
fnlhmax=arg Bandwidth grid search maximum value (if not
(default =1) “fnlh=user”).
fnlhlen=integer Bandwidth grid search length (if not “fnlh=user”).
(default = 100)
fnlhinc=integer Bandwidth grid search increment step percentage increase
(default = 10) (if not “fnlh=user”).
462—Chapter 17.Command Reference

fnlhcup=integer Stop rule: consecutive increases of objective function


(default = 10) before stop (if not “fnlh=user”).
fnlm=arg Modified multifold CV m-value: percentage of sample size
(default = 10) used in bandwidth determination (when “fnlh=cv”).
fnlfq=integer Modified multifold CV Q-value: percentage of sample size
(default = 4) used in bandwidth determination (when “fnlh=cv”).

Examples
We consider examples for three equations that estimate FCOEF using UNRATE as the depen-
dent variable, UNRATE(-1 to -2) as independent variables, and LWAGE(-4) as the functional
coefficient variable.
funcoef(eval=grid, gmin=0, gmax=10, glen=100) unrate unrate(-1)
unrate(-2) @ lwage(-4)

evaluates over a custom uniform grid from 0 to 10 with length 100.


funcoef(eval=grid, gvec=vecgrid) unrate unrate(-1) unrate(-2) @
lwage(-4)

evaluates over a custom grid provided by the values of a workfile vector called VECGRID.
funcoef(plyk=3, auxk=5) unrate unrate(-1) unrate(-2) @ lwage(-4)

estimates using local polynomial fitting with main polynomial degree 3 and auxiliary poly-
nomial degree 5. The latter is employed deriving bias, variance, and bandwidths.

Cross-references
See Chapter 38. “Functional Coefficient Regression,” on page 1651 of the User’s Guide II for
additional discussion on functional coefficients estimation.

genr Object Creation Commands || Object Assignment Commands

Generate series.

Generate series or alphas.

Syntax
genr ser_name = expression

Examples
genr y = 3 + x

generates a numeric series that takes the values from the series X and adds 3.
genr full_name = first_name + last_name
glm—463

creates an alpha series formed by concatenating the alpha series FIRST_NAME and
LAST_NAME.

Cross-references
See Chapter 6. “Working with Data,” on page 195 of User’s Guide I for discussion of generat-
ing series data.

See Series::series (p. 832) and Alpha::alpha (p. 8) in the Object Reference for a dis-
cussion of the expressions allowed in genr.

glm Interactive Use Commands

Estimate a Generalized Linear Model (GLM).

Syntax
glm(options) spec

List the glm keyword, followed by the dependent variable and a list of the explanatory vari-
ables, or an explicit linear expression.

If you enter an explicit linear specification such as “Y=C(1)+C(2)*X”, the response vari-
able will be taken to be the variable on the left-hand side of the equality (“Y”) and the linear
predictor will be taken from the right-hand side of the expression (“C(1)+C(2)*X”).

Offsets may be entered directly in an explicit linear expression or they may be entered as
using the “offset=” option.

Specification Options
family=arg Distribution family: Normal (“normal”), Poisson (“pois-
(default=“normal”) son”), Binomial Count (“binomial”), Binomial Proportion
(“binprop”), Negative Binomial (“negbin”), Gamma
(“gamma”), Inverse Gaussian (“igauss”), Exponential
Mean (“emean)”, Power Mean (“pmean”), Binomial
Squared (“binsq”).
The Binomial Count, Binomial Proportion, Negative Bino-
mial, and Power Mean families all require specification of a
distribution parameter:
n=arg (default=1) Number of trials for Binomial Count (“family=binomial”)
or Binomial Proportions (“family=binprop”) families.
fparam=arg Family parameter value for Negative Binomial (“fam-
ily=negbin”) and Power Mean (“family=pmean”) fami-
lies.
464—Chapter 17.Command Reference

link=arg Link function: Identity (“identity”), Log (“log”), Log Com-


(default=“identity”) pliment (“logc”), Logit (“logit”), Probit (“probit”), Log-log
(“loglog”), Complementary Log-log (“cloglog”), Reciprocal
(“recip”), Power (“power”), Box-Cox (“boxcox”), Power
Odds Ratio (“opow”), Box-Cox Odds Ratio (“obox”).
The Power, Box-Cox, Power Odds Ratio, and Box-Cox Odds
Ratio links all require specification of a link parameter
specified using “lparam=”.
lparam=arg Link parameter for Power (“link=power”), Box-Cox
(“link=boxcox”), Power Odds Ratio (“link=opow”) and
Box-Cox Odds Ratio (“link=obox”) link functions.
offset=arg Offset terms.
2
disp=arg Dispersion estimator: Pearson x statistic (“pearson”),
deviance statistic (“deviance”), unit (“unit”), user-speci-
fied (“user”).
The default is family specific: “unit” for Binomial Count,
Binomial Proportion, Negative Binomial, and Poison, and
“pearson” for all others.
The “deviance” option is only offered for families in the
exponential family of distributions (Normal, Poisson, Bino-
mial Count, Binomial Proportion, Negative Binomial,
Gamma, Inverse Gaussian).
dispval=arg User-dispersion value (if “disp=user”).
fwgts=arg Frequency weights.
w=arg Weight series or expression.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.

In addition to the specification options, there are options for estimation and covariance cal-
culation.
glm—465

Additional Options
optmethod = arg Optimization method: “bfgs” (BFGS); “newton” (Newton-
Raphson), “opg” or “bhhh” (OPG or BHHH), “fisher” (IRLS
– Fisher Scoring), “legacy” (EViews legacy).
Newton-Raphson is the default method.
optstep = arg Step method: “marquardt” (Marquardt); “dogleg” (Dog-
leg); “linesearch” (Line search).
Marquardt is the default method.
estmeth=arg Legacy estimation algorithm: Quadratic Hill Climbing
(default=”mar- (“marquardt”), Newton-Raphson (“newton”), IRLS - Fisher
quardt”) Scoring (“irls”), BHHH (“bhhh”).
(Applicable when “optmethod=legacy”.)
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
s Use the current coefficient values in estimator coefficient
vector as starting values (see also param (p. 564) in the
Command and Programming Reference).
s=number Specify a number between zero and one to determine start-
ing values as a fraction of EViews default values (out of
range values are set to “s=1”).
showopts / -showopts [Do / do not] display the starting coefficient values and
estimation options in the estimation output.
preiter=arg Number of IRLS pre-iterations to refine starting values
(default=0) (only available for non-IRLS estimation).
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method), “glm” (GLM
method).
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian), “fisher” (expected Hessian).
(Applicable when “optmethod=” not equal to “legacy”.
nodf Do not degree-of-freedom correct the coefficient covariance
estimate.
covlag=arg Whitening lag specification: integer (user-specified lag
(default=1) value), “a” (automatic selection).
Applicable where “cov=hac”.
466—Chapter 17.Command Reference

covinfosel=arg Information criterion for automatic selection: “aic”


(default=”aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
For settings where “cov=hac, covlag=a”.
covmaxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum
13
of T .
For settings where “cov=hac, covlag=a”.
covkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
For settings where “cov=hac”.
covbw=arg Kernel Bandwidth: “fixednw” (Newey-West fixed),
(default=“fixednw”) “andrews” (Andrews automatic), “neweywest” (Newey-
West automatic), number (User-specified bandwidth).
For settings where “cov=hac” and “covkern=” is speci-
fied.
covnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric kernel bandwidth selection (if “covbw=newey-
west”).
For settings where “cov=hac” and “covkern=” is speci-
fied.
covbwoffset=number Apply offset to automatically selected bandwidth.
For settings where “cov=hac”, “covkern=” is specified,
and “covbw=” is not user-specified.
covbwint Use integer portion of kernel bandwidth.
For settings where “cov=hac” and “covkern=” is speci-
fied.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print results.

Examples
glm(link=log) numb c ip feb
gmm—467

estimates a normal regression model with exponential mean.


glm(family=binomial, n=total) disease c snore

estimates a binomial count model with default logit link where TOTAL contains the number
of binomial trials and DISEASE is the number of binomial successes. The specification
glm(family=binprop, n=total, cov=huber, nodf) disease/total c
snore

estimates the same specification in proportion form, and computes the coefficient covari-
ance using the Huber-White sandwich with no d.f. correction.
glm(family=binprop, disp=pearson) prate mprate log(totemp)
log(totemp)^2 age age^2 sole

estimates a binomial proportions model with default logit link, but computes the coefficient
covariance using the GLM scaled covariance with dispersion computed using the Pearson
Chi-square statistic.
glm(family=binprop, link=probit, cov=huber) prate mprate
log(totemp) log(totemp)^2 age age^2 sole

estimates the same basic specification, but with a probit link and Huber-White standard
errors.
glm(family=poisson, offset=log(pyears)) los hmo white type2 type3 c

estimates a Poisson specification with an offset term LOG(PYEARS).

Cross-references
See Chapter 32. “Generalized Linear Models,” beginning on page 1491 of User’s Guide II for
discussion.

See Equation::glm (p. 153) in the Object Reference for the equivalent equation object com-
mand.

gmm Interactive Use Commands

Estimation by generalized method of moments (GMM).

Syntax
gmm(options) y x1 [x2 x3...] @ z1 [z2 z3...]
gmm(options) specification @ z1 [z2 z3...]

Follow the name of the dependent variable by a list of regressors, followed by the “@” sym-
bol, and a list of instrumental variables which are orthogonal to the residuals. Alternatively,
you can specify an expression using coefficients, an “@” symbol, and a list of instrumental
468—Chapter 17.Command Reference

variables. There must be at least as many instrumental variables as there are coefficients to
be estimated.

In panel settings, you may specify dynamic instruments corresponding to predetermined


variables. To specify a dynamic instrument, you should tag the instrument using “@DYN”,
as in “@DYN(X)”. By default, EViews will use a set of period-specific instruments corre-
sponding to lags from -2 to “-infinity”. You may also specify a restricted lag range using argu-
ments in the “@DYN” tag. For example, to use lags from-5 to “-infinity” you may enter
“@DYN(X, -5)”; to specify lags from -2 to -6, use “@DYN(X, -2, -6)” or “@DYN(X, -6, -2)”.

Note that dynamic instrument specifications may easily generate excessively large numbers
of instruments.

Options
Non-Panel GMM Options
Basic GMM Options
nocinst Do not include automatically a constant as an instrument.
method=keyword Set the weight updating method. keyword should be one of
the following: “nstep” (N-Step Iterative, or Sequential N-
Step Iterative, default), “converge” (Iterate to Convergence
or Sequential Iterate to Convergence), “simul” (Simultane-
ous Iterate to Convergence), “oneplusone” (One-Step
Weights Plus One Iteration), or “cue” (Continuously Updat-
ing”.
gmmiter=integer Number of weight iterations. Only applicable if the
“method=nstep” option is set.
w=arg Weight series or expression.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
s Use the current coefficient values in estimator coefficient
vector as starting values for equations specified by list with
AR or MA terms (see also param (p. 564) of the Com-
mand and Programming Reference).
gmm—469

s=number Determine starting values for equations specified by list


with AR or MA terms. Specify a number between zero and
one representing the fraction of TSLS estimates computed
without AR or MA terms to be used. Note that out of range
values are set to “s=1”. Specifying “s=0” initializes coeffi-
cients to zero. By default EViews uses “s=1”.
Does not apply to coefficients for AR and MA terms which
are instead set to EViews determined default values.
m=integer Maximum number of iterations.
c=number Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
l=number Set maximum number of iterations on the first-stage itera-
tion to get the one-step weighting matrix.
numericderiv / [Do / do not] use numeric derivatives only. If omitted,
-numericderiv EViews will follow the global default.
fastderiv / -fastderiv [Do / do not] use fast derivative computation. If omitted,
EViews will follow the global default.
showopts / -showopts [Do / do not] display the starting coefficient values and
estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print results.

Estimation Weighting Matrix Options


instwgt=keyword Set the estimation weighting matrix type. Keyword should
be one of the following: “tsls” (two-stage least squares),
“white” (White diagonal matrix), “hac” (Newey-West HAC,
default) or “user” (user defined).
instwgtmat=name Set the name of the user-defined estimation weighting
matrix. Only applicable if the “instwgt=user” option is set.
instlag=arg Whitening Lag specification: integer (user-specified lag
(default=1) value), “a” (automatic selection).
instinfosel=arg Information criterion for automatic whitening lag selection:
(default=“aic”) “aic” (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“instlag=a”).
470—Chapter 17.Command Reference

instmaxlag= integer Maximum lag-length for automatic selection (optional) (if


“instlag=a”). The default is an observation-based maxi-
13
mum of T .
instkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniell), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
instbw=arg Kernel Bandwidth: “fixednw” (Newey-West fixed),
(default=“fixednw”) “andrews” (Andrews automatic), “neweywest” (Newey-
West automatic), number (User-specified bandwidth).
instnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric bandwidth selection (if “instbw=neweywest”).
instbwint Use integer portion of bandwidth.

Covariance Options
cov=keyword Covariance weighting matrix type (optional): “updated”
(estimation updated), “tsls” (two-stage least squares),
“white” (White diagonal matrix), “hac” (Newey-West
HAC), “wind” (Windmeijer) or “user” (user defined).
The default is to use the estimation weighting matrix.
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
covwgtmat=name Set the name of the user-definied covariance weighting
matrix. Only applicable if the “covwgt=user” option is set.
covlag=arg Whitening lag specification: integer (user-specified lag
(default=1) value), “a” (automatic selection).
covinfosel=arg Information criterion for automatic selection: “aic”
(default=”aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
covmaxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum
13
of T .
gmm—471

covkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),


(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
covbw=arg Kernel Bandwidth: “fixednw” (Newey-West fixed),
(default=“fixednw”) “andrews” (Andrews automatic), “neweywest” (Newey-
West automatic), number (User-specified bandwidth).
covnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric kernel bandwidth selection (if “covbw=newey-
west”).
covbwint Use integer portion of bandwidth.

Panel GMM Options


cx=arg Cross-section effects method: (default) none, fixed effects
estimation (“cx=f”), first-difference estimation (“cx=fd”),
orthogonal deviation estimation (“cx=od”)
per=arg Period effects method: (default) none, fixed effects estima-
tion (“per=f”).
levelper Period dummies always specified in levels (even if one of
the transformation methods is used, “cx=fd” or “cx=od”).
wgt=arg GLS weighting: (default) none, cross-section system
weights (“wgt=cxsur”), period system weights
(“wgt=persur”), cross-section diagonal weighs
(“wgt=cxdiag”), period diagonal weights (“wgt=per-
diag”).
gmm=arg GMM weighting: 2SLS (“gmm=2sls”), White period sys-
tem covariances (Arellano-Bond 2-step/n-step)
(“gmm=perwhite”), White cross-section system
(“gmm=cxwhite”), White diagonal
(“gmm=stackedwhite”), Period system (“gmm=persur”),
Cross-section system (“gmm=cxsur”), Period heteroske-
dastic (“cov=perdiag”), Cross-section heteroskedastic
(“gmm=cxdiag”).
By default, uses the identity matrix unless estimated with
first difference transformation (“cx=fd”), in which case,
uses (Arellano-Bond 1-step) difference weighting matrix. In
this latter case, you should specify 2SLS weights
(“gmm=2sls”) for Anderson-Hsiao estimation.
472—Chapter 17.Command Reference

cov=arg Coefficient covariance method: (default) ordinary, White


cross-section system robust (“cov=cxwhite”), White
period system robust (“cov=perwhite”), White heteroske-
dasticity robust (“cov=stackedwhite”), Cross-section sys-
tem robust/PCSE (“cov=cxsur”), Period system
robust/PCSE (“cov=persur”), Cross-section heteroskedas-
ticity robust/PCSE (“cov=cxdiag”), Period heteroskedastic-
ity robust (“cov=perdiag”).
keepwgts Keep full set of GLS/GMM weights used in estimation with
object, if applicable (by default, only weights which take
up little memory are saved).
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
iter=arg Iteration control for GLS and GMM weighting specifica-
(default=“onec”) tions: perform one weight iteration, then iterate coefficients
to convergence (“iter=onec”), iterate weights and coeffi-
cients simultaneously to convergence (“iter=sim”), iterate
weights and coefficients sequentially to convergence
(“iter=seq”), perform one weight iteration, then one coef-
ficient step (“iter=oneb”).
s Use the current coefficient values in estimator coefficient
vector as starting values for equations specified by list with
AR or MA terms (see also param (p. 564) of the Com-
mand and Programming Reference).
s=number Determine starting values for equations specified by list
with AR terms. Specify a number between zero and one
representing the fraction of TSLS estimates computed with-
out AR terms to be used. Note that out of range values are
set to “s=1”. Specifying “s=0” initializes coefficients to
zero. By default EViews uses “s=1”.
Does not apply to coefficients for AR terms which are
instead set to EViews determined default values.
m=integer Maximum number of iterations.
c=number Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
l=number Set maximum number of iterations on the first-stage itera-
tion to get the one-step weighting matrix.
unbalsur Compute SUR factorization in unbalanced data using the
subset of available observations for a cluster.
gmm—473

numericderiv / [Do / do not] use numeric derivatives only. If omitted,


-numericderiv EViews will follow the global default.
fastderiv / -fastderiv [Do / do not] use fast derivative computation. If omitted,
EViews will follow the global default.
showopts / -showopts [Do / do not] display the starting coefficient values and
estimation options in the estimation output.
p Print results.

Note that some options are only available for a subset of specifications.

Examples
In a non-panel workfile, we may estimate equations using the standard GMM options. The
specification:
gmm(instwgt=white,gmmiter=2,nodf) cons c y y(-1) w @ c p(-1) k(-1)
x(-1) tm wg g t

estimates the Klein equation for consumption using GMM with a White diagonal weighting
matrix (two steps and no degree of freedom correction). The command:
gmm(method=cue,instwgt=hac,instlag=1,instkern=thann,
instbw=andrews,nodf) i c y y(-1) k(-1) @ c p(-1) k(-1) x(-1) tm
wg g t

estimates the Klein equation for investment using a Newey-West HAC weighting matrix,
with pre-whitening with 1 lag, a Tukey-Hanning kernel and the Andrews automatic band-
width routine. The estimation is performed using continuously updating weight iterations.

When working with a workfile that has a panel structure, you may use the panel equation
estimation options. The command
gmm(cx=fd, per=f) dj dj(-1) @ @dyn(dj)

estimates an Arellano-Bond “1-step” estimator with differencing of the dependent variable


DJ, period fixed effects, and dynamic instruments constructed using DJ with observation
specific lags from period t – 2 to 1.

To perform the “2-step” version of this estimator, you may use:


gmm(cx=fd, per=f, gmm=perwhite, iter=oneb) dj dj(-1) @ @dyn(dj)

where the combination of the options “gmm=perwhite” and (the default) “iter=oneb”
instructs EViews to estimate the model with the difference weights, to use the estimates to
form period covariance GMM weights, and then re-estimate the model.

You may iterate the GMM weights to convergence using:


gmm(cx=fd, per=f, gmm=perwhite, iter=seq) dj dj(-1) @ @dyn(dj)
474—Chapter 17.Command Reference

Alternately:
gmm(cx=od, gmm=perwhite, iter=oneb) dj dj(-1) x y @ @dyn(dj,-2,-6)
x(-1) y(-1)

estimates an Arellano-Bond “2-step” equation using orthogonal deviations of the dependent


variable, dynamic instruments constructed from DJ from period t – 6 to t – 2 , and ordi-
nary instruments X(-1) and Y(-1).

Cross-references
See “Generalized Method of Moments” on page 1109 and Chapter 55. “Panel Estimation,” on
page 2327 of User’s Guide II for discussion of the various GMM estimation techniques.

See also tsls (p. 612).

See Equation::gmm (p. 158) in the Object Reference for the equivalent equation object com-
mand.

heckit Interactive Use Commands

Estimate a selection equation using the Heckman ML or 2-step method.

Syntax
heckit(options) response_eqn @ selection_eqn

The response equation should be the dependent variable followed by a list of regressors. The
selection equation should be a binary dependent variable followed by a list of regressors.

Options
General Options

2step Use the Heckman 2-step estimation method. Note that this
option is incompatible with the maximum likelihood
options below.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print the estimation results.

ML Options
Note these options are not available if the "2step" option, above, is used.
heckit—475

optmethod = Optimization method: “bfgs” (BFGS); “newton” (Newton-


arg Raphson), “opg” or “bhhh” (OPG or BHHH), “legacy”
(EViews legacy).
Newton-Raphson is the default method.
optstep = arg Step method: “marquardt” (Marquardt); “dogleg” (Dog-
leg); “linesearch” (Line search).
Marquardt is the default method.
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich methods).,
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian).
(Applicable when non-legacy “optmethod=”.)
m=integer Set maximum number of iterations.
c=number Set convergence criteria.
numericderiv / [Do / do not] use numeric derivatives only. If omitted,
-numericderiv EViews will follow the global default.
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
s=number Scale EViews’ starting values by number.
r Use Newton-Raphson optimizer.
b Use BHHH optimizer.

Examples
wfopen http://www.stern.nyu.edu/~wgreene/Text/Edition7/TableF5-
1.txt
heckit ww c ax ax^2 we cit @ lfp c wa wa^2 faminc we (k618+kl6)>0
heckit(2step) ww c ax ax^2 we cit @ lfp c wa wa^2 faminc we
(k618+kl6)>0

This example replicates the Heckman Selection example given in Greene (2008, page 888),
which uses data from the Mroz (1987) study to estimate a selection model. The first line of
this example downloads the data set, the second line creates an equation object and esti-
mates it using the default maximum likelihood estimation method of Heckman Selection,
which replicates the first pane of Table 24.3 in Greene. The third line estimates the same
model, using the two-step approach, which replicates the second pane of Table 24.3.

Cross-references
See “Heckman Selection Model” on page 1471 of User’s Guide II for discussion.
476—Chapter 17.Command Reference

hconvert Object Container, Data, and File Commands

Convert an entire Haver Analytics Database into an EViews database.

Syntax
hconvert haver_path db_name

You must have a Haver Analytics database installed on your computer to use this feature. You
must also create an EViews database to store the converted Haver data before you use this
command.

Be aware that this command may be very time-consuming.

Follow the command by a full path name to the Haver database and the name of an existing
EViews database to store the Haver database. You can include a path name to the EViews
database not in the default path.

Examples
dbcreate hdata
hconvert d:\haver\haver hdata

The first line creates a new (empty) database named HDATA in the default directory. The
second line converts all the data in the Haver database and stores it in the HDATA database.

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews and Haver databases.

See also dbcreate (p. 426), db (p. 424), hfetch (p. 477) and hlabel (p. 478).

help Global Commands

Displays the documentation of an EViews command or procedure.

Syntax
help topic

Examples
help @cumsum

displays the documentation for the cumulative sum function.


help alpha.freq
hist—477

displays the documentation for the alpha series freq procedure.

hfetch Object Container, Data, and File Commands

Fetch a series from a Haver Analytics database into a workfile.

hfetch reads one or more series from a Haver Analytics Database into the active workfile.
You must have a Haver Analytics database installed on your computer to use this feature.

Syntax
hfetch(database_name) series_name

hfetch, if issued alone on a command line, will bring up a Haver dialog box which has
fields for entering both the database name and the series names to be fetched. If you provide
the database name (including the full path) in parentheses after the hfetch command,
EViews will read the database and copy the series requested into the current workfile. It will
also display information about the series on the status line. The database name is optional if
a default database has been specified.

hfetch can read multiple series with a single command. List the series names, each sepa-
rated by a space.

Examples
hfetch(c:\data\us1) pop gdp xyz

reads the series POP, GDP, and XYZ from the US1 database into the current active workfile,
performing frequency conversions if necessary.

Cross-references
See also Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews and Haver databases. Additional information on EViews frequency conversion is
provided in “Frequency Conversion” on page 177 of User’s Guide I.

See also dbcreate (p. 426), db (p. 424), hconvert (p. 476) and hlabel (p. 478).

hist Interactive Use Commands

Histogram and descriptive statistics of a series.

The hist command computes descriptive statistics and displays a histogram for the series.

Syntax
hist(options) series_name
478—Chapter 17.Command Reference

Options
p Print the histogram.

Examples
hist lwage

Displays the histogram and descriptive statistics of LWAGE.

Cross-references
See “Histogram and Stats” on page 450 of User’s Guide I for a discussion of the descriptive
statistics reported in the histogram view.

See distplot (p. 1282) in the Object Reference for a more full-featured and customizable
method of constructing histograms, and Series::hist (p. 798) in the Object Reference for
the equivalent series object view command.

hlabel Object Container, Data, and File Commands

Display a Haver Analytics database series description.

hlabel reads the description of a series from a Haver Analytics Database and displays it on
the status line at the bottom of the EViews window. Use this command to verify the contents
of a Haver database series name.

You must have a Haver Analytics database installed on your computer to use this feature.

Syntax
hlabel(database_name) series_name

hlabel, if issued alone on a command line, will bring up a Haver dialog box which has
fields for entering both the database name and the series names to be examined. If you pro-
vide the database name in parentheses after the hlabel command, EViews will read the data-
base and find the key information about the series in question, such as the start date, end
date, frequency, and description. This information is displayed in the status line at the bot-
tom of the EViews window. Note that the database_name should refer to the full path to the
Haver database but need not be specified if a default database has been specified in
HAVERDIR.INI.

If several series names are placed on the line, hlabel will gather the information about
each of them, but the information display may scroll by so fast that only the last will be vis-
ible.
hpf—479

Examples
hlabel(c:\data\us1) pop

displays the description of the series POP in the US1 database.

Cross-references
See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion of
EViews and Haver databases.

See also hfetch (p. 477) and hconvert (p. 476).

hpf Interactive Use Commands

Smooth a series using the Hodrick-Prescott filter.

Syntax
hpf(options) series_name filtered_name [@ cycle_name]

Smoothing Options
The degree of smoothing may be specified as an option. You may specify the smoothing as a
value, or using a power rule:
lambda=arg Set smoothing parameter value to arg; a larger number
results in greater smoothing.
power=arg Set smoothing parameter value using the frequency power
(default=2) rule of Ravn and Uhlig (2002) (the number of periods per
year divided by 4, raised to the power arg, and multiplied
by 1600).
Hodrick and Prescott recommend the value 2; Ravn and
Uhlig recommend the value 4.

If no smoothing option is specified, EViews will use the power rule with a value of 2.

Other Options
prompt Force the dialog to appear from within a program.
p Print the graph of the smoothed series and the original
series.

Examples
hpf(lambda=1000) gdp gdp_hp

smooths the GDP series with a smoothing parameter “1000” and saves the smoothed series
as GDP_HP.
480—Chapter 17.Command Reference

Cross-references
See “Hodrick-Prescott Filter” on page 625 of User’s Guide I for details.

See Series::hpf (p. 799) of the Object Reference for the equivalent series object command.

import Object Container, Data, and File Commands

Imports data from a foreign file or a previously saved workfile into the current default
workfile. The import command lets you perform four different types of data importing:
dated reads, match-merge reads, sequential reads, and appends.

Dated imports can only be performed if the destination workfile is a dated workfile. You
must specify the date structure of the source data as part of the import command. EViews
will then match the date structure of the source with that of the destination, and perform
frequency conversion if necessary.

Match-merge imports require both a source ID series and a destination ID series. EViews will
read the source data into the destination workfile based upon matched values of the two ID
series.

Sequential imports will read the source data into the destination workfile by matching the
first observation of the source file to the first observation in the destination workfile's cur-
rent sample, then the second observation of the source with the second observation in the
destination's current sample, and so on.

Appended imports simply append the source data to the end of the destination workfile.

Syntax
The general form of the import command is:
import([type=], options) source_description import_specification [@smpl
smpl_string] [@genr genr_string] [@rename rename_string]

where the syntax for import_specification depends on whether the read is a dated (“Dated
Imports” on page 482), match-merge (“Match-Merge Import” on page 484), sequential
(“Sequential Read” on page 486), or appended import (“Appended Read” on page 487).
• Source_description should contain a description of the file from which the data is to be
imported. The specification of the description is usually just the path and file name of
the file, however you can also specify more precise information. See wfopen (p. 640)
for more details on the specification of source_description.
• The optional “type=” option may be used to specify a source type. For the most part,
you should not need to specify a “type=” option as EViews will automatically deter-
import—481

mine the type from the filename. The following table summaries the various source
formats and along with the corresponding “type=” keywords:

Option Keywords
Access “access”
Aremos-TSD “a”, “aremos”, “tsd”
Binary “binary”
dBASE “dbase”
Excel (through 2003) “excel”
Excel 2007 (xml) “excelxml”
EViews Workfile ---
Gauss Dataset “gauss”
GiveWin/PcGive “g”, “give”
HTML “html”
Lotus 1-2-3 “lotus”
ODBC Dsn File “dsn”
ODBC Query File “msquery”
ODBC Data Source “odbc”
MicroTSP Workfile “dos”, “microtsp”
MicroTSP Mac Workfile “mac”
RATS 4.x “r”, “rats”
RATS Portable / TROLL “l”, “trl”
SAS Program “sasprog”
SAS Transport “sasxport”
SPSS “spss”
SPSS Portable “spssport”
Stata “stata”
Text / ASCII “text”
TSP Portable “t”, “tsp”

• The optional @smpl keyword may be used to specify that data is only imported for
the observations specified by smpl_string. By default, the import will use all of the
observations in the workfile. If @smpl is included, but no smpl_string is included,
then the current default workfile sample is used.
• The optional @genr keyword may be used to generate a new series in the workfile as
part of the import procedure. genr_string may be any valid series creation expression,
482—Chapter 17.Command Reference

and can be an expression based upon one of the imported series. See genr (p. 462)
for information on valid expressions.
• The optional @rename keyword may be used to rename some of the imported series
where rename_string contains pairs of old object names followed by the new names.
See rename (p. 573) for additional discussion.

In the remainder of this discussion, we examine each of the different import types in greater
depth.

Dated Imports
The syntax for a dated import command is:
import([type=], options) source_description @freq frequency start_date [@smpl
smpl_string] [@genr genr_string] [@rename rename_string]

The import_specification consists of the @freq keyword followed by a frequency argument


specifying the frequency of the source data and a start_date to specify the starting date of
the source data. See wfcreate (p. 634) for details on the forms that frequency may take.
Basic Options
resize Extend the destination workfile (if necessary) to include
the entire range of the source data.
link Link the object to the source data so that the values can be
refreshed at a later time.
mode=arg Set the behavior for handling name conflicts when an
(default=“o”) imported series already exists in the destination workfile.
arg can be “o” (Completely replace existing series with
source series. Note that values outside of the range of the
source data will be overwritten with NAs), “u” (Overwrite
existing series only for values within the range of the
source data. Destination values outside of the source range
will be unchanged), “ms” (Overwrite existing series, unless
source value is an NA, in which case keep destination val-
ues), “md” (Only overwrite NA values in destination
series), “r” (rename any conflicts), or “p” (do not import
any series which have a name conflict).
page=page_name Optional name for the page into which the data should be
imported.
tr=integer Truncate long series names to integer characters. The
default value of integer is 24.
prompt Force the dialog to appear from within a program.
import—483

Frequency Conversion Options


The following options control the frequency conversion method when copying series and
group objects into a workfile page and converting from low to high frequency:
c=arg Low to high conversion methods: “r” or “repeata” (con-
stant match average), “d” or “repeats” (constant match
sum), “q” or “quada” (quadratic match average), “t” or
“quads” (quadratic match sum), “linearf” (linear match
first), “i” or “linearl” (linear match last), “cubicf” (cubic
match first), “c” or “cubicl” (cubic match last), “pointf”
(point first), “pointl” (point last).

When importing data from a higher frequency source into a lower frequency destination:
c=arg High to low conversion methods removing NAs: “a” (aver-
age of the nonmissing observations), “s” (sum of the non-
missing observations), “f” (first nonmissing observation),
“l” (last nonmissing observation), “x” (maximum nonmiss-
ing observation), “m” (minimum nonmissing observation).
High to low conversion methods propagating NAs: “an” or
“na” (average, propagating missings), “sn” or “ns” (sum,
propagating missings), “fn” or “nf” (first, propagating
missings), “ln” or “nl” (last, propagating missings), “xn”
or “nx” (maximum, propagating missings), “mn” or “nm”
(minimum, propagating missings).

Examples
import c:\temp\quarterly.xls @freq q 1990

will import the file QUARTERLY.XLS into the current default workfile. The source file has a
quarterly frequency, starting at 1990.
import(c=s) c:\temp\quarterly.xls range="GDP_SHEET" @freq q 1990
@rename gdp_per_capita gdp

will import from same file, but instead will use the data on the Excel sheet called
“GDP_SHEET”, and will rename the series GDP_PER_CAPITA to GDP. A frequency conver-
sion method using the sum of the nonmissing observations is used rather than the default
average.
import(mode=p) c:\temp\annual.txt @freq a 1990 @smpl 1994 1996

will import data from a text file called annual.txt, into the current default workfile. Any data
in the text file that already exists in the destination workfile will be ignored, and for the
remaining series, only the dates between 1994 and 1996 will be imported.
484—Chapter 17.Command Reference

Additionally, specifying the “tr” option causes EViews 10 to truncate long series names to 24
characters (by default) instead of 300. This will let programs written for EViews 9 continue
to work with EViews 10:
fetch(d=eia, link, tr) coal.average_employees.al-tot.a

The “tr” option can also be set to a number between 0 and 300:
fetch(d=eia, link, tr=20) coal.average_employees.al-tot.a

Match-Merge Import
Syntax
import(options) source_description @id id @destid destid [@smpl smpl_string]
[@genr genr_string] [@rename rename_string]

The import_specification consists of the @id keyword and at least one ID series in the
source file, followed by the @destid keyword and at least one ID series in the destination
workfile. The two sets of ID series should be compatible, in that they should contain a sub-
set of identical values that provide information on how observations from the two files
should be matched. If one of the ID series is a date series, you should surround it with the
@date( ) keyword.
Options
resize Extend the destination workfile (if necessary) to include
the entire range of the source data.
link Link the object to the source data so that the values can be
refreshed at a later time.
mode=arg Set the behavior for handling name conflicts when an
(default=“o”) imported series already exists in the destination workfile.
arg can be “o” (Completely replace existing series with
source series. Note that values outside of the range of the
source data will be overwritten with NAs), “u” (Overwrite
existing series only for values within the range of the
source data. Destination values outside of the source range
will be unchanged), “ms” (Overwrite existing series, unless
source value is an NA, in which case keep destination val-
ues), “md” (Only overwrite NA values in destination
series), “r” (rename any conflicts), or “p” (do not import
any series which have a name conflict).
nacat Treat “NA” values as a category when copying using gen-
eral match merge operations.
propnas Propogate NAs / partial periods evaluate to NAs when con-
verting.
import—485

c=arg Set the match merge contraction method.


If you are importing a numeric source series by general
match merge, the argument can be one of: “mean”, “med”
(median), “max”, “min”, “sum”, “sumsq” (sum-of
squares), “var” (variance), “sd” (standard deviation),
“skew” (skewness), “kurt” (kurtosis), “quant” (quantile,
used with “quant=” option), “obs” (number of observa-
tions), “nas” (number of NA values), “first” (first observa-
tion in group), “last” (last observation in group), unique”
(single unique group value, if present), “none” (disallow
contractions).
If importing an alpha series, only the non-summary meth-
ods “max”, “min”, “obs”, “nas”, first”, “last”, “unique”
and “none” are supported.
For importing of numeric series, the default contraction
method is “c=mean”; for copying of alpha series, the
default is “c=unique”.
page=page_name Optional name for the page into which the data should be
imported.
prompt Force the dialog to appear from within a program.

Most of the conversion options should be self-explanatory. As for the others: “first” and
“last” give the first and last non-missing observed for a given group ID; “obs” provides the
number of non-missing values for a given group; “nas” reports the number of NAs in the
group; “unique” will provide the value in the source series if it is the identical for all obser-
vations in the group, and will return NA otherwise; “none” will cause the import to fail if
there are multiple observations in any group—this setting may be used if you wish to pro-
hibit all contractions.
Examples
import(c=max, type=excel) c:\data\stateunemp.xls @id states
@destid states

will import the file STATEUNEMP.XLS using the ID series STATES in both files as the match
merge criteria. The maximum value is used as a contraction method. Note that although the
“type=excel” option was used, it was not necessary since EViews will automatically detect
the file type based on the file's extension (.xls).
import c:\data\stategdp.txt colhead=3 delim=comma @id states
@date(year) @destid states @date

will import the file STATEGDP.TXT, specifying that there are three lines of column headers,
and the delimiter for the text file is a comma. The series STATES is used as an ID series in
both files, along with a date series (YEAR for the source file, and the default EViews date
series, @DATE, for the destination workfile). Note that this type of import, with both a
486—Chapter 17.Command Reference

cross-section ID and a date ID is most commonly employed for importing data into panel
workfiles.
import c:\data\cagdp.xls @id states @date(year) @destid states
@date @genr states="CA"

will import the file CAGDP.XLS into the current workfile. In this particular case the source
file is a time series file for a single state, California. Since the importing is being done into a
panel workfile, the @genr keyword is used to generate a series containing the state identi-
fier, CA, which is then used as the source ID.

Sequential Read
Syntax
import(options) source_description [@smpl smpl_string] [@genr genr_string]
[@rename rename_string]

No import_specification is required for a sequential read.


Options
resize Extend the destination workfile (if necessary) to include the
entire range of the source data.
link Link the object to the source data so that the values can be
refreshed at a later time.
mode=arg Set the behavior for handling name conflicts when an
(default=“o”) imported series already exists in the destination workfile.
arg can be “o” (Completely replace existing series with
source series. Note that values outside of the range of the
source data will be overwritten with NAs), “u” (Overwrite
existing series only for values within the range of the
source data. Destination values outside of the source range
will be unchanged), “ms” (Overwrite existing series, unless
source value is an NA, in which case keep destination val-
ues), “md” (Only overwrite NA values in destination
series), “r” (rename any conflicts), or “p” (do not import
any series which have a name conflict).
page=page_name Optional name for the page into which the data should be
imported.
prompt Force the dialog to appear from within a program.

Examples
import(resize) sales.dta @smpl @all

will import the Stata file SALES.DTA into the current workfile, using the entire workfile
range. If the sales.dta file contains more observations that the current workfile, the current
workfile is resized to accommodate the extra rows of data.
importattr—487

Appended Read
Syntax
import(options) source_description @append [@genr genr_string] [@rename
rename_string]

The import_specification consists of the @append keyword. Note that the @smpl keyword
is not supported for appended import.
Options
link Link the object to the source data so that the values can be
refreshed at a later time.
mode=arg Set the behavior for handling name conflicts when an
(default=“o”) imported series already exists in the destination workfile.
arg can be “o” (Completely replace existing series with
source series. Note that values outside of the range of the
source data will be overwritten with NAs), “r” (rename any
conflicts), or “p” (do not import any series which have a
name conflict).
page=page_name Optional name for the page into which the data should be
imported.
prompt Force the dialog to appear from within a program.

Examples
import(page=demand) demand.txt @append

will append the text file, DEMAND.TXT, to the bottom of the page “demand” in the current
workfile.

Cross-references
See Chapter 2. “Workfile Basics,” on page 29 of User’s Guide I for a discussion of workfiles.

See also wfopen (p. 640), copy (p. 411), pageload (p. 546), read (p. 570), fetch (p. 449),
wfsave (p. 656), and pagesave (p. 548).

importattr Object Container, Data, and File Commands

Imports observation values stored inside one or more series in a second workfile page into
the attribute fields of objects within the current workfile page.

Syntax
importattr(options) source_page [@keep keeplist @drop droplist]
488—Chapter 17.Command Reference

The source page should contain one series whose values are the names of the objects into
which the attributes should be imported, and one or more additional series containing the
values of each attribute to be imported. By default, the procedure will assume there is an
alpha series called NAME in the source page that contains the object names. The “name=”
option can be used to specify that a different series in the source page contains the object
names.

Values in the name column will always be converted into legal EViews names before match-
ing to object names in the current workfile. (For example, any spaces will be replaced by
underscores.)

Typically, the name of the series in the source workfile will be used as the attribute name
inside the current workfile. However, if an object in the source workfile has a display name
set, this value will be used for the attribute name instead. Display names must be used to
specify attribute names if your attribute names contain spaces since spaces are not allowed
within EViews object names.

For numeric series, attribute values will be imported using the formatting currently set for
the series spreadsheet view of the source series.

By default, all series in the source page will be used as attribute values (except the series
containing object names). To import only a subset of series as attributes, name patterns can
be provided in the @keep and @drop arguments to restrict which series will be used.

importattr is most often useful when importing custom attributes from an external file. It
is common for foreign data files, such as Excel files, to have one file (or sheet in Excel) con-
taining the data, and a separate file (or sheet) containing the attributes, or meta-data, of
each series. In such cases the pageload command can be used to read in the attribute file
as a separate page in your workfile, and then importattr can be used to assign them to the
data page.

Options
mode=arg Specify how the procedure treats existing attribute values
in the current workfile page. arg may be "o" or "overwrite"
(clears all existing attribute values in the object before
applying the imported attribute value), “u” or “update”
(clears existing attribute values only for the attributes that
are being imported), “m” or “merge” (keeps existing values
if the imported value of the attribute is empty), “md”
(keeps all existing non-empty values. only empty values
will be replaced with the imported values).
trim=string Remove string from the start and end of the attribute name.
name=arg Specify the name of the alpha series in the source page
containing the names of objects in the target page.
importmat—489

Examples
importattr(name=objnames) attributes @keep attr1 attr2

Imports values from series ATTR1 and ATTR2 in the page “Attributes” into attributes “attr1”
and “attr2” of objects in the current workfile. The series OBJNAMES in the page “Attributes”
specifies which objects in the current workfile should have their attribute values updated.
importattr(name=objnames, trim=":") attributes @keep attr1 attr2

removes the “:” from the start and end of the attribute name, if present, since EViews adds
that character in the label view.

Cross-references
See “Workfile Details Display” on page 51 and “Label” on page 493 of User’s Guide I for a
discussion of the workfile details display and, for example, the series object label view.

importmat Object Container, Data, and File Commands

Imports data from a foreign file into a matrix object in the current workfile.

Syntax
The general form of the importmat command is:
importmat([type=], options) source_description import_specification
• Source_description should contain a description of the file from which the data is to be
imported. The specification of the description is usually just the path and file name of
the file, however you can also specify more precise information. See wfopen (p. 640)
for more details on the specification of source_description.
• The optional “type=” option may be used to specify a source type. For the most part,
you should not need to specify a “type=” option as EViews will automatically deter-
mine the type from the filename. The following table summaries the various source
formats and along with the corresponding “type=” keywords:

Option Keywords
Excel (through 2003) “excel”
Excel 2007 (xml) “excelxml”
HTML “html”
Text / ASCII “text”
490—Chapter 17.Command Reference

Options
name=arg Specify a name for the created matrix object.
display=arg Specify a display name for the created matrix object.
page=page_name Optional name for the page into which the matrix should
be created.
mode=o Overwrite an existing object with the same name (only
applicable if the name option is used).

• import_specification can be used to provide additional information about the file to be


read. The details of import_specification will depend upon the type of file being
imported.

Excel Files
The syntax for reading Excel files is:
importmat(options) source_description [table_description] [variables_description]

The following table_description elements may be used when reading Excel data:
• “range = arg”, where arg is a range of cells to read from the Excel workbook, follow-
ing the standard Excel format [worksheet!][topleft_cell[:bottomright_cell]].
If the worksheet name contains spaces, it should be placed in single quotes. If the
worksheet name is omitted, the cell range is assumed to refer to the currently active
sheet. If only a top left cell is provided, a bottom right cell will be chosen automati-
cally to cover the range of non-empty cells adjacent to the specified top left cell. If
only a sheet name is provided, the first set of non-empty cells in the top left corner of
the chosen worksheet will be selected automatically. As an alternative to specifying
an explicit range, a name which has been defined inside the excel workbook to refer
to a range or cell may be used to specify the cells to read.
• “byrow”, transpose the incoming data. This option allows you to read files where the
series are contained in rows (one row per series) rather than columns.

The optional variables_description may be formed using the elements:


• “colhead=int”, number of table rows to be treated as column headers.
• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w”(EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”. This option is rarely required.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
importmat—491

• “scan=[int| all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a "range=" argument is not specified,
then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the "na=" argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the "scan=" argument to instruct EViews to look at more rows. In addition, you may
want to specify a the "na=" value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the data (default is 1). This
option may be used to start reading rows from partway through the table.
• “lastobs = int”, last observation to be read from the data (default is last observation
of the file). This option may be used to read only part of the file, which may be useful
for testing.

Excel Examples
importmat "c:\data files\data.xls"

loads the active sheet of DATA.XLSX into a new untitled matrix object.
importmat(name=mymat) "c:\data files\data.xls" range="GDP data"

reads the data contained in the “GDP data” sheet of “Data.XLS” into the MYMAT object.

HTML Files
The syntax for reading HTML pages is:
importmat(options) source_description [table_description] [variables_description]

The following table_description elements may be used when reading an HTML file or page:
• “table = arg”, where arg specifies which HTML table to read in an HTML file/page
containing multiple tables.
When specifying arg, you should remember that tables are named automatically fol-
lowing the pattern “Table01”, “Table02”, “Table03”, etc. If no table name is specified,
the largest table found in the file will be chosen by default. Note that the table num-
bering may include trivial tables that are part of the HTML content of the file, but
would not normally be considered as data tables by a person viewing the page.
• “skip = int”, where int is the number of rows to discard from the top of the HTML
table.
• “byrow”, transpose the incoming data. This option allows you to import files where
the series are contained in rows (one row per series) rather than columns.

The optional variables_description may be formed using the elements:


492—Chapter 17.Command Reference

• “colhead=int”, number of table rows to be treated as column headers.


• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w”(EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”. This option is rarely used.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
• “scan=[int|all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a "range=" argument is not specified,
then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the "na=" argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the "scan=" argument to instruct EViews to look at more rows. In addition, you may
want to specify a the "na=" value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the table of data (default is 1).
This option may be used to start reading rows from partway through the table.
• “lastobs = int”, last observation to be read from the table of data (default is last
observation of the file). This option may be used to read only part of the file, which
may be useful for testing.

HTML Examples
importmat "c:\data.html"

loads into a new untitled matrix object the data located in the HTML file “Data.HTML”
located on the C:\ drive
importmat(type=html, name=forexmat)
"http://www.tradingroom.com.au/apps/mkt/forex.ac" colhead=3

loads into a matrix object called FOREXMAT the data with the given URL located on the
website site “http://www.tradingroom.com.au”. The column header is set to three rows.

Text and Binary Files


The syntax for reading text or binary files is:
importmat(options) source_description [table_description] [variables_description]

If a table_description is not provided, EViews will attempt to read the file as a free-format
text file. The following table_description elements may be used when reading a text or
binary file:
importmat—493

• “ftype = [ascii|binary]” specifies whether numbers and dates in the file are stored in
a human readable text (ASCII), or machine readable (Binary) form.
• “rectype = [crlf|fixed|streamed]” describes the record structure of the file:
“crlf”, each row in the output table is formed using a fixed number of lines from
the file (where lines are separated by carriage return/line feed sequences). This is
the default setting.
“fixed”, each row in the output table is formed using a fixed number of charac-
ters from the file (specified in “reclen= arg”). This setting is typically used for
files that contain no line breaks.
“streamed”, each row in the output table is formed by reading a fixed number of
fields, skipping across lines if necessary. This option is typically used for files that
contain line breaks, but where the line breaks are not relevant to how rows from
the data should be formed.
• “reclines =int”, number of lines to use in forming each row when “rectype=crlf”
(default is 1).
• “reclen=int”, number of bytes to use in forming each row when “rectype=fixed”.
• “recfields=int”, number of fields to use in forming each row when “rec-
type=streamed”.
• “skip=int”, number of lines (if rectype is “crlf”) or bytes (if rectype is not “crlf”) to
discard from the top of the file.
• “comment=string“, where string is a double-quoted string, specifies one or more
characters to treat as a comment indicator. When a comment indicator is found,
everything on the line to the right of where the comment indicator starts is ignored.
• “emptylines=[keep|drop]”, specifies whether empty lines should be ignored
(“drop”), or treated as valid lines (“keep”) containing missing values. The default is
to ignore empty lines.
• “tabwidth=int”, specifies the number of characters between tab stops when tabs are
being replaced by spaces (default=8). Note that tabs are automatically replaced by
spaces whenever they are not being treated as a field delimiter.
• “fieldtype=[delim|fixed|streamed|undivided]”, specifies the structure of fields within
a record:
“Delim”, fields are separated by one or more delimiter characters
“Fixed”, each field is a fixed number of characters
“Streamed”, fields are read from left to right, with each field starting immediately
after the previous field ends.
“Undivided”, read entire record as a single series.
494—Chapter 17.Command Reference

• “quotes=[single|double|both|none]”, specifies the character used for quoting fields,


where “single” is the apostrophe, “double” is the double quote character, and “both”
means that either single or double quotes are allowed (default is “both”). Characters
contained within quotes are never treated as delimiters.
• “singlequote“, same as “quotes = single”.
• “delim=[comma|tab|space|dblspace|white|dblwhite]”, specifies the character(s) to
treat as a delimiter. “White” means that either a tab or a space is a valid delimiter. You
may also use the abbreviation “d=” in place of “delim=”.
• “custom="arg1"”, specifies custom delimiter characters in the double quoted string.
Use the character “t” for tab, “s” for space and “a” for any character.
• “mult=[on|off]”, to treat multiple delimiters as one. Default value is “on” if “delim”
is “space”, “dblspace”, “white”, or “dblwhite”, and “off” otherwise.
• “endian = [big|little]”, selects the endianness of numeric fields contained in binary
files.
• “string = [nullterm|nullpad|spacepad]”, specifies how strings are stored in binary
files. If “nullterm”, strings shorter than the field width are terminated with a single
zero character. If “nullpad”, strings shorter than the field width are followed by extra
zero characters up to the field width. If “spacepad”, strings shorter than the field
width are followed by extra space characters up to the field width.
• “byrow”, transpose the incoming data. This option allows you to import files where
the series are contained in rows (one row per series) rather than columns.
• “lastcol”, include implied last column. For lines that end with a delimiter, this option
adds an additional column. When importing a csv file, lines which have the delimiter
as the last character (for example: “name, description, date”), EViews normally deter-
mines the line to have 3 columns. With the above option, EViews will determine the
line to have 4 columns. Note this is not the same as a line containing “name, descrip-
tion, date”. In this case, EViews will always determine the line to have 3 columns
regardless if the option is set.

A central component of the table_description element is the format statement. You may
specify the data format using the following table descriptors:
• Fortran Format:
fformat=([n1]Type[Width][.Precision], [n2]Type[Width][.Precision], ...)
where Type specifies the underlying data type, and may be one of the following,
I - integer
F - fixed precision
E - scientific
importmat—495

A - alphanumeric
X - skip
and n1, n2, ... are the number of times to read using the descriptor (default=1). More
complicated Fortran compatible variations on this format are possible.
• Column Range Format:
rformat="[n1]Type[Width][.Precision], [n2]Type[Width][.Precision], ...)"
where optional type is “$” for string or “#” for number, and n1, n2, n3, n4, etc. are the
range of columns containing the data.
• C printf/scanf Format:
cformat="fmt"
where fmt follows standard C language (printf/scanf) format rules.

The optional variables_description may be formed using the elements:


• “colhead=int”, number of table rows to be treated as column headers.
• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w”(EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”. This option is rarely used.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
• “scan=[int|all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a "range=" argument is not specified,
then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the "na=" argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the "scan=" argument to instruct EViews to look at more rows. In addition, you may
want to specify a the "na=" value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the table of data (default is 1).
This option may be used to start reading rows from partway through the table.
• “lastobs = int”, last observation to be read from the table of data (default is last
observation of the file). This option may be used to read only part of the file, which
may be useful for testing.

Text and Binary File Examples (.txt, .csv, etc.)


importmat c:\data.csv skip=5
496—Chapter 17.Command Reference

reads “Data.CSV” into a new unnamed matrix object, skipping the first 5 rows.
importtbl(type=text, name=matrix01) c:\date.txt delim=comma

loads the comma delimited data DATE.TXT into the MATRIX01 matrix object.

Cross-references
See Chapter 2. “Workfile Basics,” on page 29 of User’s Guide I for a discussion of workfiles.

See also wfopen (p. 640), copy (p. 411), pageload (p. 546), read (p. 570), fetch (p. 449),
wfsave (p. 656), and pagesave (p. 548).

importtbl Object Container, Data, and File Commands

Imports data from a foreign file into a table object in the current workfile.

Syntax
The general form of the importtbl command is:
importtbl([type=], options) source_description import_specification
• Source_description should contain a description of the file from which the data is to be
imported. The specification of the description is usually just the path and file name of
the file, however you can also specify more precise information. See wfopen (p. 640)
for more details on the specification of source_description.
• The optional “type=” option may be used to specify a source type. For the most part,
you should not need to specify a “type=” option as EViews will automatically deter-
mine the type from the filename. The following table summaries the various source
formats and along with the corresponding “type=” keywords:

Option Keywords
Excel (through 2003) “excel”
Excel 2007 (xml) “excelxml”
HTML “html”
Text / ASCII “text”

Options
name=arg Specify a name for the created table object.
importtbl—497

display=arg Specify a display name for the created table object.


page=page_name Optional name for the page into which the table should be
created.
mode=o Overwrite an existing object with the same name (only
applicable if the name option is used).

• import_specification can be used to provide additional information about the file to be


read. The details of import_specification will depend upon the type of file being
imported.

Excel Files
The syntax for reading Excel files is:
importtbl(options) source_description [table_description] [variables_description]

The following table_description elements may be used when reading Excel data:
• “range = arg”, where arg is a range of cells to read from the Excel workbook, follow-
ing the standard Excel format [worksheet!][topleft_cell[:bottomright_cell]].
If the worksheet name contains spaces, it should be placed in single quotes. If the
worksheet name is omitted, the cell range is assumed to refer to the currently active
sheet. If only a top left cell is provided, a bottom right cell will be chosen automati-
cally to cover the range of non-empty cells adjacent to the specified top left cell. If
only a sheet name is provided, the first set of non-empty cells in the top left corner of
the chosen worksheet will be selected automatically. As an alternative to specifying
an explicit range, a name which has been defined inside the excel workbook to refer
to a range or cell may be used to specify the cells to read.
• “byrow”, transpose the incoming data. This option allows you to read files where the
series are contained in rows (one row per series) rather than columns.

The optional variables_description may be formed using the elements:


• “colhead=int”, number of table rows to be treated as column headers.
• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w”(EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”. This option is rarely required.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
• “scan=[int| all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a "range=" argument is not specified,
498—Chapter 17.Command Reference

then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the "na=" argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the "scan=" argument to instruct EViews to look at more rows. In addition, you may
want to specify a the "na=" value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the data (default is 1). This
option may be used to start reading rows from partway through the table.
• “lastobs = int”, last observation to be read from the data (default is last observation
of the file). This option may be used to read only part of the file, which may be useful
for testing.

Excel Examples
importtbl "c:\data files\data.xls"

loads the active sheet of DATA.XLSX into a new untitled table object.
importtbl(name=mytbl) "c:\data files\data.xls" range="GDP data"

reads the data contained in the “GDP data” sheet of “Data.XLS” into the MYTBL object.

HTML Files
The syntax for reading HTML pages is:
importtbl(options) source_description [table_description] [variables_description]

The following table_description elements may be used when reading an HTML file or page:
• “table = arg”, where arg specifies which HTML table to read in an HTML file/page
containing multiple tables.
When specifying arg, you should remember that tables are named automatically fol-
lowing the pattern “Table01”, “Table02”, “Table03”, etc. If no table name is specified,
the largest table found in the file will be chosen by default. Note that the table num-
bering may include trivial tables that are part of the HTML content of the file, but
would not normally be considered as data tables by a person viewing the page.
• “skip = int”, where int is the number of rows to discard from the top of the HTML
table.
• “byrow”, transpose the incoming data. This option allows you to import files where
the series are contained in rows (one row per series) rather than columns.

The optional variables_description may be formed using the elements:


• “colhead=int”, number of table rows to be treated as column headers.
importtbl—499

• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w”(EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”. This option is rarely used.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
• “scan=[int|all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a "range=" argument is not specified,
then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the "na=" argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the "scan=" argument to instruct EViews to look at more rows. In addition, you may
want to specify a the "na=" value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the table of data (default is 1).
This option may be used to start reading rows from partway through the table.
• “lastobs = int”, last observation to be read from the table of data (default is last
observation of the file). This option may be used to read only part of the file, which
may be useful for testing.

HTML Examples
importtbl "c:\data.html"

loads into a new untitled table object the data located in the HTML file “Data.HTML”
located on the C:\ drive
importtbl(type=html, name=forextbl)
"http://www.tradingroom.com.au/apps/mkt/forex.ac" colhead=3

loads into a table object called FOREXTBL the data with the given URL located on the web-
site site “http://www.tradingroom.com.au”. The column header is set to three rows.

Text and Binary Files


The syntax for reading text or binary files is:
importtbl(options) source_description [table_description] [variables_description]

If a table_description is not provided, EViews will attempt to read the file as a free-format
text file. The following table_description elements may be used when reading a text or
binary file:
500—Chapter 17.Command Reference

• “ftype = [ascii|binary]” specifies whether numbers and dates in the file are stored in
a human readable text (ASCII), or machine readable (Binary) form.
• “rectype = [crlf|fixed|streamed]” describes the record structure of the file:
“crlf”, each row in the output table is formed using a fixed number of lines from
the file (where lines are separated by carriage return/line feed sequences). This is
the default setting.
“fixed”, each row in the output table is formed using a fixed number of charac-
ters from the file (specified in “reclen= arg”). This setting is typically used for
files that contain no line breaks.
“streamed”, each row in the output table is formed by reading a fixed number of
fields, skipping across lines if necessary. This option is typically used for files that
contain line breaks, but where the line breaks are not relevant to how rows from
the data should be formed.
• “reclines =int”, number of lines to use in forming each row when “rectype=crlf”
(default is 1).
• “reclen=int”, number of bytes to use in forming each row when “rectype=fixed”.
• “recfields=int”, number of fields to use in forming each row when “rec-
type=streamed”.
• “skip=int”, number of lines (if rectype is “crlf”) or bytes (if rectype is not “crlf”) to
discard from the top of the file.
• “comment=string“, where string is a double-quoted string, specifies one or more
characters to treat as a comment indicator. When a comment indicator is found,
everything on the line to the right of where the comment indicator starts is ignored.
• “emptylines=[keep|drop]”, specifies whether empty lines should be ignored
(“drop”), or treated as valid lines (“keep”) containing missing values. The default is
to ignore empty lines.
• “tabwidth=int”, specifies the number of characters between tab stops when tabs are
being replaced by spaces (default=8). Note that tabs are automatically replaced by
spaces whenever they are not being treated as a field delimiter.
• “fieldtype=[delim|fixed|streamed|undivided]”, specifies the structure of fields within
a record:
“Delim”, fields are separated by one or more delimiter characters
“Fixed”, each field is a fixed number of characters
“Streamed”, fields are read from left to right, with each field starting immediately
after the previous field ends.
“Undivided”, read entire record as a single series.
importtbl—501

• “quotes=[single|double|both|none]”, specifies the character used for quoting fields,


where “single” is the apostrophe, “double” is the double quote character, and “both”
means that either single or double quotes are allowed (default is “both”). Characters
contained within quotes are never treated as delimiters.
• “singlequote“, same as “quotes = single”.
• “delim=[comma|tab|space|dblspace|white|dblwhite]”, specifies the character(s) to
treat as a delimiter. “White” means that either a tab or a space is a valid delimiter. You
may also use the abbreviation “d=” in place of “delim=”.
• “custom="arg1"”, specifies custom delimiter characters in the double quoted string.
Use the character “t” for tab, “s” for space and “a” for any character.
• “mult=[on|off]”, to treat multiple delimiters as one. Default value is “on” if “delim”
is “space”, “dblspace”, “white”, or “dblwhite”, and “off” otherwise.
• “endian = [big|little]”, selects the endianness of numeric fields contained in binary
files.
• “string = [nullterm|nullpad|spacepad]”, specifies how strings are stored in binary
files. If “nullterm”, strings shorter than the field width are terminated with a single
zero character. If “nullpad”, strings shorter than the field width are followed by extra
zero characters up to the field width. If “spacepad”, strings shorter than the field
width are followed by extra space characters up to the field width.
• “byrow”, transpose the incoming data. This option allows you to import files where
the series are contained in rows (one row per series) rather than columns.

A central component of the table_description element is the format statement. You may
specify the data format using the following table descriptors:
• Fortran Format:
fformat=([n1]Type[Width][.Precision], [n2]Type[Width][.Precision], ...)
where Type specifies the underlying data type, and may be one of the following,
I - integer
F - fixed precision
E - scientific
A - alphanumeric
X - skip
and n1, n2, ... are the number of times to read using the descriptor (default=1). More
complicated Fortran compatible variations on this format are possible.
• Column Range Format:
rformat="[n1]Type[Width][.Precision], [n2]Type[Width][.Precision], ...)"
502—Chapter 17.Command Reference

where optional type is “$” for string or “#” for number, and n1, n2, n3, n4, etc. are the
range of columns containing the data.
• C printf/scanf Format:
cformat="fmt"
where fmt follows standard C language (printf/scanf) format rules.

The optional variables_description may be formed using the elements:


• “colhead=int”, number of table rows to be treated as column headers.
• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w”(EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”. This option is rarely used.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
• “scan=[int|all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a "range=" argument is not specified,
then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the "na=" argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the "scan=" argument to instruct EViews to look at more rows. In addition, you may
want to specify a the "na=" value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the table of data (default is 1).
This option may be used to start reading rows from partway through the table.
• “lastobs = int”, last observation to be read from the table of data (default is last
observation of the file). This option may be used to read only part of the file, which
may be useful for testing.

Text and Binary File Examples (.txt, .csv, etc.)


importtbl c:\data.csv skip=5

reads “Data.CSV” into a new unnamed table object, skipping the first 5 rows.
importtbl(type=text, name=table01) c:\date.txt delim=comma

loads the comma delimited data DATE.TXT into the TABLE01 table object.

Cross-references
See Chapter 2. “Workfile Basics,” on page 29 of User’s Guide I for a discussion of workfiles.
liml—503

See also wfopen (p. 640), copy (p. 411), pageload (p. 546), read (p. 570), fetch (p. 449),
wfsave (p. 656), and pagesave (p. 548).

liml Interactive Use Commands

Limited Information Maximum Likelihood and K-class Estimation.

Syntax
liml(options) y c x1 [x2 x3 ...] @ z1 [z2 z3 ...]
liml(options) specification @ z1 [z2 z3 ...]

To use the liml command, list the dependent variable first, followed by the regressors, then
any AR or MA error specifications, then an “@”-sign, and finally, a list of exogenous instru-
ments.

You may estimate nonlinear equations or equations specified with formulas by first provid-
ing a specification, then listing the instrumental variables after an “@”-sign. There must be
at least as many instrumental variables as there are independent variables. All exogenous
variables included in the regressor list should also be included in the instrument list. A con-
stant is included in the list of instrumental variables, unless the noconst option is specified.

Options
noconst Do not include a constant in the instrumental list. Without
this option, a constant will always be included as an instru-
ment, even if not specified explicitly.
w=arg Weight series or expression.
wtype=arg Weight specification type: inverse standard deviation
(default=“istdev”) (“istdev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
kclass=number Set the value of k in the K-class estimator. If omitted, LIML
is performed, and k is calculated as part of the estimation
procedure.
se = arg Set the standard-error calculation type: IV based
(default=“iv”) (“se=iv”), K-Class based (“se=kclass”), Bekker
(“se=bekk”), or Hansen, Hausman, and Newey
(“se=hhn”).
m=integer Set maximum number of iterations.
504—Chapter 17.Command Reference

c=number Set convergence criterion. The criterion is based upon the


maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
numericderiv / [Do / do not] use numeric derivatives only. If omitted,
-numericderiv EViews will follow the global default.
fastderiv / [Do / do not] use fast derivative computation. If omitted,
-fastderiv EViews will follow the global default.
Available only for legacy estimation (“optmeth=legacy”).
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Examples
liml gdp c cpi inc @ lw lw(-1)

calculates a LIML estimation of GDP on a constant, CPI, and INC, using a constant, LW, and
LW(-1) as instruments.

Cross-references
See “Limited Information Maximum Likelihood and K-Class Estimation” on page 1105 of
User’s Guide II for discussion.

See Equation::liml (p. 179) for the equivalent equation object method.

load Object Container, Data, and File Commands

Load a workfile.

Provided for backward compatibility. Same as wfopen (p. 640).

logclear Programming Commands

Clears the log window corresponding to the program.

Use this command any time from within a program to clear the program log.
logclose—505

Syntax
logclear(options)

Options
name=arg Name of the message log.
filename=arg Name of the message log file to store the messages.

Examples
To clear the contents of the message log FIRSTRUN:
logclear(name=”firstrun”)

To clear the contents of the message log FIRSTRUN and delete the file C:\MYFILE.TXT:
logclear(name=”firstrun”, filename=”c:\myfile.txt”)

Cross-references
See “Program Message Logging” on page 152 for details.

See also logmode (p. 506), logmsg (p. 509), logclose (p. 505), and logsave (p. 509).

logclose Programming Commands

Closes one or more or all message log windows.

Use this command any time from the command line or from within a program to close the
log windows.

Syntax
logclose logwindow_list

where logwindow_list is a list of log windows to close: “@all” will close all log windows,
while “arg1 arg2 arg3” will close the log windows ARG1, ARG2, and ARG3.

Examples
To close all log windows:
logclose @all

To close the log windows FIRSTRUN and SECONDRUN:


logclose firstrun secondrun

Cross-references
See “Program Message Logging” on page 152 for details.
506—Chapter 17.Command Reference

See also logmode (p. 506), logmsg (p. 509), and logsave (p. 509).

logeval Programming Commands

Sends result of the command to a log window.

Syntax
logeval command

Examples
logeval @pagelist

Sends to a log window a string containing the names of all the pages in the current active
workfile.
logeval @abs(3)

Sends to a log window the absolute value of 3.

Cross-references
See “Program Message Logging” on page 152 for details.

See also logmode (p. 506), logmsg (p. 509), logclose (p. 505), and logsave (p. 509).

logit Interactive Use Commands

Estimate binary models with logistic errors.

Provide for backward compatibility. Equivalent to issuing the command, binary with the
option “(d=l)”.

See binary (p. 382).

logmode Programming Commands

Set the log settings of specified message types.

Activates or deactivates the logging of specified message types if message types are set to be
program controlled.

Controls the output of the messages to a log window with a specified name and/or to a file
on disk.

Syntax
logmode(options) msgtype_list
logmode—507

where msgtype_list is a list of the message types to update.

Options
name=arg Name of the message log and message log window. Default
name is: PROGRAM_NAME.
filename=arg Name of the message log file on disk to store the messages.
autosave=on/off Turns on/off automatic saving of the message logs on disk.
clearfile Deletes the message log file (specified by filename option).
clear Clears the log window.
float Makes the log window floating.
timestamp, ts Adds a timestamp in front of the message.

Message type options


all/-all [Show/Do not show] all messages.
error/-error, e/-e [Show/Do not show] error messages.
logmsg /-logmsg, [Show/Do not show] logmsg messages.
l/ -l
program/-program, [Show/Do not show] program lines.
p/-p
statusline/-sta- [Show/Do not show] status line messages.
tusline, s / -s
hideprogline/- [Hide/Do not hide] the program line when reporting errors
hideprogline encountered during execution.
addin/-addin [Show/Do not show] messages generally appropriate for
addin error reporting. addin is equivalent to the command
and program mode (“Program Modes” on page 151) state-
ments:
logmode hideprogline -error
mode quiet
debug Show messages generally appropriate for debugging of pro-
grams. Equivalent to the command:
logmode -hideprogline error

Note that using logmode with debug will override all subsequent (in either the current pro-
gram or any program run using exec or run), logmode with hideprog and -error specifi-
cations. In particular, debug will override subsequent logmode addin statements.
508—Chapter 17.Command Reference

Examples
logmode p

turns on logging and directs the output to the window PROGRAM_NAME. Note that by
default all message types are initially turned off.
logmode error -p

Building on the first command, this activates the logging of errors and deactivates the log-
ging of program lines. The error messages will be displayed on a window with name PRO-
GRAM_NAME.
logmode -all s

turns off logging of all types, with the exception of status line messages. The status line mes-
sages will be displayed on a window with name PROGRAM_NAME. Note the order of mes-
sage types is important. For example,
logmode p -all

will initially activate the logging of program lines, but following p with -all will deactivate
program lines as well as any other messages that have been previously activated. The pro-
gram lines will be displayed in a window with name PROGRAM_NAME
logmode(name="firstrun") l

turns on logging of logmsg messages and outputs the messages on a window with name
FIRSTRUN.
logmode(name="") l

Building on the previous command, this will no longer output the messages on the window
with name FIRSTRUN, but instead on a window with name PROGRAM_NAME.
logmode(name="secondrun", filename="c:\myfile.txt", autosave=on)

turns on logging, sends the output to the window SECONDRUN, and writes the messages to
a file with name myFile.txt.
logmode(name="thirdrun", clear, ts, float, autosave=off)

directs messages to a window with name THIRDRUN, clears the window, adds a timestamp
to all messages, makes the window floating, and turns off the autosave.
logmode(name="fourthrun", autosave=on )

turns on logging, sends messages to a window with name FOURTHRUN, and writes mes-
sages to a file with name program_name.txt

Cross-references
See “Program Message Logging” on page 152 for details. See also “Program Modes” on
page 151.
logsave—509

See also logclear (p. 504), logmsg (p. 509), logclose (p. 505), and logsave (p. 509).

logmsg Programming Commands

Adds a line of text to the program log.

Syntax
logmsg(options) text

Options
name=arg Name of the message log where messages will be added.
filename=arg Name of the message log where messages will be stored.

Example
logmsg About to iterate through list of states

appends the text “About to iterate through list of states” to the program log with name PRO-
GRAM_NAME.
logmsg(name="firstrun") Exiting list iteration

appends the text "Exiting list iteration" on the program log with name FIRSTRUN.
logmsg(filename="c:\myfile.txt") Restarting list iteration

appends the text "Restarting list iteration" on the program log with name FIRSTRUN. It also
stores the message in the file c:\myfile.txt.

Cross-references
See “Program Message Logging” on page 152 for details.

See also logclear (p. 504), logmode (p. 506), logclose (p. 505), and logsave (p. 509).

logsave Programming Commands

Saves the program log to a text file.

Syntax
logsave(options) destination

where destination is the location and filename for saving the log file (for types text and rtf)
or the text object name (for type textobj)
510—Chapter 17.Command Reference

Options
type=arg Type TEXT to save the log as a TXT file (default).
Type RTF to save the log as an RTF file (to preserve syntax
coloring).
Type TEXTOBJ to save the log as a TEXTOBJECT in the cur-
rent workfile.
name=arg Name of the message log, the contents of which will be
written in the log file.
append Append to the file, if the file exists. Default behavior clears
the contents of the file. (Not supported for type=rtf).

Example
logsave c:\EViews\myprog.text

saves the contents of the program log to the text file MYPROG, in the “C:\EViews” directory.
logsave(name="firstrun", type=rtf) c:\EViews\myprog.rtf

saves the contents of the program log FIRSTRUN to the rtf file MYPROG, in the "C:\EViews"
directory.
logsave(name="secondrun", type=textobj) mytextobj

saves the contents of the program log SECONDRUN to a text object MYTEXTOBJ in the cur-
rent workfile.
logsave(name="thirdrun", type=text, append) c:\EViews\myprog.txt

saves the contents of the program log THIRDRUN to the text file MYPROG, in the
"C:\EViews" directory. The output will be appended at the end of the file.

Cross-references
See “Program Message Logging” on page 152 for details.

See also logclear (p. 504), logmode (p. 506), logclose (p. 505), and logmsg (p. 509).

ls Interactive Use Commands

When the current workfile has a panel structure, ls also estimates cross-section weighed
least squares, feasible GLS, and fixed and random effects models.

Syntax
ls(options) y x1 [x2 x3 ...]
ls(options) specification
ls—511

For linear specifications, list the dependent variable first, followed by a list of the indepen-
dent variables. Use a “C” if you wish to include a constant or intercept term; unlike some
programs, EViews does not automatically include a constant in the regression. You may add
AR, MA, SAR, and SMA error specifications, a D fractional differencing term, and PDL spec-
ifications for polynomial distributed lags. If you include lagged variables, EViews will adjust
the sample automatically, if necessary.

Both dependent and independent variables may be created from existing series using stan-
dard EViews functions and transformations. EViews treats the equation as linear in each of
the variables and assigns coefficients C(1), C(2), and so forth to each variable in the list.

Linear or nonlinear single equations may also be specified by explicit equation. You should
specify the equation as a formula. The parameters to be estimated should be included
explicitly: “C(1)”, “C(2)”, and so forth (assuming that you wish to use the default coefficient
vector “C”). You may also declare an alternative coefficient vector using coef and use these
coefficients in your expressions.

Options
Non-Panel LS Options
indicator Include indicator saturation detection as part of estimation
routine.
w=arg Weight series or expression.
Note: we recommend that, absent a good reason, you
employ the default settings Inverse std. dev. weights
(“wtype=istdev”) with EViews default scaling
(“wscale=eviews”) for backward compatibility with ver-
sions prior to EViews 7.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
z Turn off backcasting in ARMA models where “arma=cls”.
optmethod = arg Optimization method for nonlinear least squares and
ARMA: “bfgs” (BFGS); “newton” (Newton-Raphson),
“opg” or “bhhh” (OPG or BHHH), “kohn” (Kohn-Ansley
for ARMA estimated by ML or GLS), or “legacy” (EViews
legacy for nonlinear least squares and ARMA estimated by
CLS).
Gauss-Newton is the default method.
512—Chapter 17.Command Reference

optstep = arg Step method for nonlinear least squares and ARMA: “mar-
quardt” (Marquardt); “dogleg” (Dogleg); “linesearch” (Line
search).
Marquardt is the default method.
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method available for non-
linear least squares or ARMA estimated by CLS), “hac”
(Newey-West HAC, available for nonlinear least squares or
ARMA estimated by CLS)..
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian).
(Applicable when non-legacy “optmethod=”.)
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
covlag=arg Whitening lag specification: integer (user-specified lag
(default=1) value), “a” (automatic selection).
covinfosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
covmaxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum
13
of T .
covkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
covbw=arg Kernel Bandwidth: “fixednw” (Newey-West fixed),
(default=“fixednw” “andrews” (Andrews automatic), “neweywest” (Newey-
) West automatic), number (User-specified bandwidth).
covnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric kernel bandwidth selection (if “covbw=newey-
west”).
covbwint Use integer portion of bandwidth.
m=integer Set maximum number of iterations.
ls—513

c=scalar Set convergence criterion. The criterion is based upon the


maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
arma=arg ARMA estimation method: “ml” (maximum likelihood);
“gls” (generalized least squares), “cls” (conditional least
squares).
Not applicable to ARFIMA models which always estimate
using maximum likelihood.
armastart=arg ARMA coefficient starting values: “auto” (automatic)
“fixed” (legacy EViews fixed); “random” (random draw);
“user” (user-specified).
Applicable when “arma=ml” or “arma=gls”.
s Use the current coefficient values in estimator coefficient
vector as starting values for equations specified by list with
AR or MA terms when “arma=cls” (see also param
(p. 564) of the Command and Programming Reference).
s=number Determine starting values for equations specified by list
with AR or MA terms when “arma=cls”. Specify a number
between zero and one representing the fraction of prelimi-
nary least squares estimates computed without AR or MA
terms to be used. Note that out of range values are set to
“s=1”. Specifying “s=0” initializes coefficients to zero. By
default EViews uses “s=1”.
Does not apply to coefficients for AR and MA terms which
are set to EViews determined default values.
numericderiv / [Do / do not] use numeric derivatives only. If omitted,
-numericderiv EViews will follow the global default.
fastderiv / -fastderiv [Do / do not] use fast derivative computation. If omitted,
EViews will follow the global default.
Available only for legacy estimation (“optmeth=legacy”).
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method available for non-
linear least squares or ARMA estimated by CLS), “hac”
(Newey-West HAC, available for nonlinear least squares or
ARMA estimated by CLS)., “hc” (extended heteroskedastic-
ity consistent), “hcuser” (user-specified heteroskedastic-
ity), “cr” (cluster robust).
The extended “hc” methods are only available for linear
specifications.
514—Chapter 17.Command Reference

hctype=arg (default Extended heteroskedasticity consistent method: “hc0” (no


“hc2”) d.f. adjustment), “hc1” (d.f. adjusted), “hc2”, “hc3”,
“hc4”, “hc4m”, “hc5”, when “cov=hc”.
userwt=arg Name of series containing user-diagonal weights (if
“cov=hcuser”)
crtype=arg (default Cluster robust weighting method: “cr0” (no finite sample
“cr1”) correction), “cr1” (finite sample correction), “hc2”, “hc3”,
“hc4”, “hc4m”, “hc5”, when “cov=cr”.
crname=arg Cluster robust series name, when “cov=cr”.
k=arg Parameter for “cov=hc, hctype=hc5” or “cov=cr,
(default = 0.7) crtype=cr5”.
k1=arg Parameter for “cov=hc, hctype=hc4m” or “cov=cr,
(default = 1.0) crtype=cr4m”.
k2=arg Parameter for “cov=hc, hctype=hc4m” or “cov=cr,
(default = 1.5) crtype=cr4m”.
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Note: not all options are available for all equation methods. See the User’s Guide II for details
on each estimation method.
Non-Panel Indicator Saturation Options
For use if “indicator” option is specified.
noiis Do not search for impulse terms.
sis Search for step-shift terms.
trend Search for trend terms.
pval=number Set the terminal condition p-value used to determine the
(default = 0.05) stopping point of each search path
nolm Do not perform AR LM diagnostic test.
arpval=number Set p-value used in AR LM diagnostic test.
(default = 0.025)
ls—515

arlags=int (default Set number of lags used in AR LM diagnostic test.


= 1)
noarch Do not perform ARCH LM diagnostic test.
archpval=number Set p-value used in ARCH LM diagnostic test.
(default = 0.025)
archlags=int Set number of lags used in ARCH LM diagnostic test.
(default = 1)
nojb Do not perform Jarque-Bera normality diagnostic test.
jbpval=number Set p-value used in Jarque-Bera normality diagnostic test.
(default = 0.025)
nopet Do not perform Parsimonious Encompassing diagnostic
test.
petpval=number Set p-value used in Parsimonious Encompassing diagnostic
(default = 0.025) test.
nogum Do not include the general model as a candidate for model
selection.
noempty Do not include the empty model as a candidate for model
selection.
ic =arg Set the information criterion used in model selection: “AIC”
(Akaike information criteria, default), “BIC” (Schwarz
information criteria), “HQ” (Hannan-Quin criteria).
blocks=int Override the EViews’ determination of the number of
blocks in which to split the estimation sample.

Panel LS Options
cx=arg Cross-section effects: (default) none, fixed effects
(“cx=f”), random effects (“cx=r”).
per=arg Period effects: (default) none, fixed effects (“per=f”), ran-
dom effects (“per=r”).
wgt=arg GLS weighting: (default) none, cross-section system
weights (“wgt=cxsur”), period system weights
(“wgt=persur”), cross-section diagonal weighs
(“wgt=cxdiag”), period diagonal weights (“wgt=per-
diag”).
516—Chapter 17.Command Reference

cov=arg Coefficient covariance method: (default) ordinary, White


cross-section system (period clustering) robust
(“cov=cxwhite” or “cov=percluster”), White period sys-
tem (cross-section clustering) robust (“cov=perwhite” or
“cov=cxcluster”), White heteroskedasticity robust
(“cov=stackedwhite”), White two-way cluster robust
(cov=bothcluster”), Cross-section system robust/PCSE
(“cov=cxsur”), Period system robust/PCSE (“cov=per-
sur”), Cross-section heteroskedasticity robust/PCSE
(“cov=cxdiag”), Period heteroskedasticity robust/PCSE
(“cov=perdiag”).
keepwgts Keep full set of GLS weights used in estimation with object,
if applicable (by default, only small memory weights are
saved).
rancalc=arg Random component method: Swamy-Arora (“ran-
(default=“sa”) calc=sa”), Wansbeek-Kapteyn (“rancalc=wk”), Wallace-
Hussain (“rancalc=wh”).
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
iter=arg (default= Iteration control for GLS specifications: perform one weight
“onec”) iteration, then iterate coefficients to convergence
(“iter=onec”), iterate weights and coefficients simultane-
ously to convergence (“iter=sim”), iterate weights and
coefficients sequentially to convergence (“iter=seq”), per-
form one weight iteration, then one coefficient step
(“iter=oneb”).
Note that random effects models currently do not permit
weight iteration to convergence.
unbalsur Compute SUR factorization in unbalanced data using the
subset of available observations for a cluster.
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
ls—517

s Use the current coefficient values in estimator coefficient


vector as starting values for equations specified by list with
AR terms (see also param (p. 564) of the Command and
Programming Reference).
s=number Determine starting values for equations specified by list
with AR terms. Specify a number between zero and one
representing the fraction of preliminary least squares esti-
mates computed without AR terms to be used. Note that
out of range values are set to “s=1”. Specifying “s=0” ini-
tializes coefficients to zero. By default EViews uses “s=1”.
Does not apply to coefficients for AR terms which are
instead set to EViews determined default values.
numericderiv / [Do / do not] use numeric derivatives only. If omitted,
-numericderiv EViews will follow the global default.
fastderiv / -fastderiv [Do / do not] use fast derivative computation. If omitted,
EViews will follow the global default.
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
prompt Force the dialog to appear from within a program.
p Print basic estimation results.

Examples
ls m1 c uemp inf(0 to -4) @trend(1960:1)

estimates a linear regression of M1 on a constant, UEMP, INF (from current up to four lags),
and a linear trend.
ls(z) d(tbill) c inf @seas(1) @seas(1)*inf ma(2)

regresses the first difference of TBILL on a constant, INF, a seasonal dummy, and an interac-
tion of the dummy and INF, with an MA(2) error. The “z” option turns off backcasting.
coef(2) beta
param beta(1) .2 beta(2) .5 c(1) 0.1
ls(cov=white) q = beta(1)+beta(2)*(l^c(1) + k^(1-c(1)))

estimates the nonlinear regression starting from the specified initial values. The
“cov=white” option reports heteroskedasticity consistent standard errors.
ls r = c(1)+c(2)*r(-1)+div(-1)^c(3)

estimates an UNTITLED nonlinear equation.


ls(cx=f, per=f) n w k ys c
518—Chapter 17.Command Reference

estimates an UNTITLED equation in a panel workfile using both cross-section and period
fixed effects.
ls(cx=f, wgt=cxdiag) n w k ys c

estimates an UNTITLED equation in a panel workfile with cross-section weights and fixed
effects.

Cross-references
Chapter 20. “Basic Regression Analysis,” on page 1011 and Chapter 21. “Additional Regres-
sion Tools,” on page 1029 of User’s Guide II discuss the various regression methods in
greater depth.

Chapter 13. “Special Expression Reference,” on page 323 describes special terms that may
be used in ls specifications.

See Chapter 55. “Panel Estimation,” on page 2327 of User’s Guide II for a discussion of panel
equation estimation.

See Equation::ls (p. 181) for the equivalent equation object method command.

matplace Matrix Utility Commands

Place submatrix in matrix.

Place matrix object at a specified location in a matrix.

Syntax
matplace(m1, m2[, n1, n2])

Places the matrix object m2 into m1 at row n1 and column n2. The sizes of the two matrices
do not matter, as long as m1 is large enough to contain all of m2 with the upper left cell of
m2 placed at row n1 and column n2.

Examples
matrix(100,5) m1
matrix(100,2) m2
matplace(m1, m2, 1, 1)

Cross-references
See also rowplace (p. 581) and colplace (p. 410).
midas—519

midas Interactive Use Commands

Estimates an equation using Mixed Data Sampling (MIDAS) regression.

MIDAS regression is an estimation technique which allows for data sampled at different fre-
quencies to be used in the same regression.

Syntax
midas(options) y x1 [x2 x3 ...] @ z1page\z1 [z2page\z2 ...]

where y, x1, etc., are the dependent and explanatory variables in the current page frequency,
and z1page\z1 and z2page\z2 are the high frequency variable page\series specification.

You may not include ARMA terms in a MIDAS regression.

Options
General options
midwgt=arg MIDAS weight method: step function(“step”), normalized
exponential Almon (“expalmon”), normalized beta func-
tion (“beta”), U-MIDAS (“umidas”), Auto-search/GETS
(“autogets”) or the default Almon/PDL weighting
(“almon”).
lag=arg Method for specifying the number of lags of the high fre-
quency regressor to use: lag selection (“auto”), fixed
(“fixed”). The default is “lag=fixed”.
maxlag=arg Maximum number of lags of the high frequency regressor
to use when using lag selection. For use when “lag=auto”.
The default value is 4.
fixedlag=arg Fixed number of lags of the high frequency regressor to
use. For use when “lags=fixed”. The default value is 4.
steps=integer Stepsize (number of high frequency periods to group). For
use when “midwgt=step”.
polynomial=integer Polynomial degree. For use when Almon/PDL weighting is
employed.
beta=arg Beta function restriction: none (“none”), trend coefficient
equals 1 (“trend”), endpoints coefficient equals 0 (“end-
point”), both trend and endpoints restriction (“both”).
For use when “midwgt=beta”. The default is
“beta=none”.
520—Chapter 17.Command Reference

optmethod = arg Optimization method for nonlinear estimation: “bfgs”


(BFGS); “newton” (Newton-Raphson), “opg” or “bhhh”
(OPG or BHHH), “hybrid” (initial BHHH followed by
BFGS).
Hybrid is the default method.
optstep = arg Step method for nonlinear estimation: “marquardt” (Mar-
quardt); “dogleg” (Dogleg); “linesearch” (Line search).
Marquardt is the default method.
cov=arg Covariance method for nonlinear models: “ordinary”
(default method based on inverse of the estimated informa-
tion matrix), “huber” or “white” (Huber-White sandwich).
covinfo = arg Information matrix method for nonlinear models: “opg”
(OPG); “hessian” (observed Hessian).
freq = key Set the frequency conversion method. Key can be “first”
(the higher frequency data are used from the first observa-
tion in the lower frequency period), “last” (default, the
higher frequency data are used from the last observation in
the lower frequency), or “match” (a specific date matching
series from each page is used).
freqsrc = arg Set the source date matching series. Only applies if
freq=match is used.
freqdest = arg Set the destination date matching series. Only applies if
freq=match is used.
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
s Use the current coefficient values in estimator coefficient
vector as starting values in nonlinear estimation (see also
param (p. 564) of the Command and Programming Ref-
erence).
s=number Determine starting values for nonlinear estimation.. Specify
a number between zero and one representing the fraction
of preliminary EViews chosen values. Note that out of
range values are set to “s=1”. Specifying “s=0” initializes
coefficients to zero. By default EViews uses “s=1”.
midas—521

showopts / [Do / do not] display the starting coefficient values and


-showopts estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Auto-search/GETS options
pval=number Set the terminal condition p-value used to determine the
(default = 0.05) stopping point of each search path
nolm Do not perform AR LM diagnostic test.
arpval=number Set p-value used in AR LM diagnostic test.
(default = 0.025)
arlags=int (default Set number of lags used in AR LM diagnostic test.
= 1)
noarch Do not perform ARCH LM diagnostic test.
archpval=number Set p-value used in ARCH LM diagnostic test.
(default = 0.025)
archlags=int Set number of lags used in ARCH LM diagnostic test.
(default = 1)
nojb Do not perform Jarque-Bera normality diagnostic test.
jbpval=number Set p-value used in Jarque-Bera normality diagnostic test.
(default = 0.025)
nopet Do not perform Parsimonious Encompassing diagnostic
test.
petpval=number Set p-value used in Parsimonious Encompassing diagnostic
(default = 0.025) test.
nogum Do not include the general model as a candidate for model
selection.
noempty Do not include the empty model as a candidate for model
selection.
ic =arg Set the information criterion used in model selection: “AIC”
(Akaike information criteria, default), “BIC” (Schwarz
information criteria), “HQ” (Hannan-Quin criteria).
blocks=int Override the EViews’ determination of the number of
blocks in which to split the estimation sample.
522—Chapter 17.Command Reference

Examples
midas(fixedlag=9, midwgt=beta, beta=endpoint) realgdp c realgdp(-
1) @ monthlypage\emp(-5)

estimates a MIDAS beta weight specification using the low frequency dependent variable
REALGDP and regressors C and REALGDP(-1), and 9 beta weighted lags of EMP(-5) from
the “monthlypage” workfile page. The beta weight function places zero restrictions on the
endpoint coefficient.
midas(maxlag=12, lag=auto) realgdp c realgdp(-1) @
monthlypage\emp(-5)

estimates the same equation using PDL/Almon weights. The number of lags is chosen auto-
matically with a maximum of 12 lags.

Cross-references
Chapter 30. “Midas Regression,” on page 1411 of the User’s Guide II discusses the specifica-
tion and estimation of MIDAS regression models in EViews.

mtos Matrix Utility Commands

Convert matrix object to a series or group.

Matrix-TO-Series object: convert the data in a matrix object to a series, alpha, or group.

Syntax
mtos(vector, series[, sample])
mtos(svector, alpha[, sample])
mtos(matrix, group[, sample, prefix])
mtos(matrix, group[, prefix])

The number of observations in the sample must match the row size of the matrix to be con-
verted. If no sample is provided, the matrix is written into the series using the current work-
file sample.

For the matrix forms of the command, the prefix parameter is a string. If the target group
object does not exist, the group is created and populated with series named <prefix>1,
<prefix>2, etc. If the prefix is omitted, the default prefix is “SER”.

Examples
mtos(mom,gr1)

converts the first column of the matrix MOM to the first series in the group GR1, the second
column of MOM to the second series in GR1, and so on. The current workfile sample length
nrnd—523

must match the row length of the matrix MOM. If GR1 is an existing group object, the num-
ber of series in GR1 must match the number of columns of MOM. If a group object named
GR1 does not exist, EViews creates GR1 with the first series named SER1, the second series
named SER2, and so on.
series col1
series col2
group g1 col1 col2
sample s1 1951 1990
mtos(m1,g1,s1)

The first two lines declare series objects, the third line declares a group object, the fourth
line declares a sample object, and the fifth line converts the columns of the matrix M1 to
series in group G1 using sample S1. This command will generate an error if M1 is not a
40  2 matrix.
Cross-references
See Chapter 11. “Matrix Language,” on page 279 for further discussion and examples of the
use of matrices.

See also stom (p. 598), stomna (p. 599), and @convert (p. 764).

nrnd Object Assignment Commands

Generate random normal draws.

The nrnd command fills series, vector, and matrix objects with (pseudo) random values
drawn from a standard normal distribution. When used with a series, the nrnd command
ignores the current sample and fills the entire object.

Syntax
nrnd(object_name)

Fill object_name with normal random numbers.

Examples
matrix(10, 3) m1
nrnd(m1)

Cross-references
For random generator functions, see “Statistical Distributions,” on page 686 and in particu-
lar, @mrnd (p. 1000), @mnrnd (p. 982), and @rmvnorm (p. 1085).
524—Chapter 17.Command Reference

For related commands, see rnd (p. 575), rndint (p. 576), and rmvnorm (p. 574). See also
rndseed (p. 577).

open Object Container, Data, and File Commands || Programming Commands

Opens a program file, or text (ASCII) file.

This command should be used to open program files or text (ASCII) files for editing.

You may also use the command to open workfiles or databases. This use of the open com-
mand for this purposes is provided for backward compatibility. We recommend instead that
you use the new commands wfopen (p. 640) and pageload (p. 546) to open a workfile,
and dbopen (p. 428) to open databases.

Syntax
open(options) [path\]file_name

You should provide the name of the file to be opened including the extension (and option-
ally a path), or the file name without an extension but with an option identifying its type.
Specified types always take precedence over automatic type identification. If a path is not
provided, EViews will look for the file in the default directory.

Files with the “.PRG” extension will be opened as program files, unless otherwise specified.
Files with the “.TXT” extension will be opened as text files, unless otherwise specified.

For backward compatibility, files with extensions that are recognized as database files are
opened as EViews databases, unless an explicit type is specified. Similarly, files with the
extensions “.WF” and “.WF1”, and foreign files with recognized extensions will be opened
as workfiles, unless otherwise specified.

All other files will be read as text files.

Options
p Open file as program file.
t Open file as text file.
type=arg (“prg” Specify text or program file type using keywords.
or “txt”)

Examples
open finfile.txt

opens a text file named “Finfile.TXT” in the default directory.


open "c:\program files\my files\test1.prg"
optimize—525

opens a program file named “Test1.PRG” from the specified directory.


open a:\mymemo.tex

opens a text file named “Mymemo.TEX” from the A: drive.

Cross-references
See wfopen (p. 640) and pageload (p. 546) for commands to open files as workfiles or
workfile pages, and dbopen (p. 428) for opening database files.

optimize Programming Commands

Find the solution to a user-defined optimization problem.

The optimize command calls the EViews optimizer to find the optimal control values for a
subroutine defined elsewhere in the program file or files.

Syntax
optimize(options) subroutine_name(arguments)

You should follow the optimize command keyword with options and subroutine_name, the
name of a defined subroutine in your program (or included programs).

The subroutine must contain at least two arguments.

By default EViews will interpret the first argument as the output of the subroutine and will
use it as the value to optimize. If the objective contains more than one value, as in a series
or vector, EViews will optimize the sum of the values. The second argument is, by default,
used to define the control parameters for which EViews will find the optimal values.

Since the objective and controls are defined by a standard EViews subroutine, the arguments
of the subroutine may correspond to numbers, strings, and various EViews objects such as
series, vectors, scalars.

Options
Optimization Objective and Controls
The default optimization objective is to maximize the first argument of the subroutine. You
may use the following optimization options to change the optimization objective and to
specify the coefficients (control parameters):
526—Chapter 17.Command Reference

max [=integer] Maximize the subroutine objective or sum of the values of


the subroutine objective (default).
By default the first argument of the subroutine is used as
the maximization objective. You may change the objective
to another argument by specifying an integer argument
location.
min [=integer] Minimize the subroutine objective or sum of the values of
the subroutine objective.
By default the first argument of the subroutine is used as
the minimization objective. You may change the objective
to another argument by specifying an integer argument
location.
ls [=integer] Perform least squares minimization of the sum of squared
values of the subroutine objective. (The objective argu-
ment cannot be a scalar value when using this option.)
By default the first argument of the subroutine is used as
the minimization objective. You can change the objective to
another argument by specifying an integer argument loca-
tion.
ml [=integer] Perform maximum likelihood estimation of the sum of the
values of the subroutine objective. (The objective argu-
ment cannot be a scalar value when using this option.)
By default the first argument of the subroutine is used as
the maximization objective. You can change the objective
to another argument by specifying an integer argument
location.
Note that the “ml” option specifies the same optimization
as when using the “max” option, but permits a different set
of Hessian matrix choices.
coef=integer Specify the argument number of the function that contains
(default = 2) the coefficient controls for the optimization.
If the argument is a vector or matrix, each element of the
vector or matrix will be treated as a coefficient. If the argu-
ment is a series, each element of the series within the cur-
rent workfile sample will be treated as a coefficient.
The default value is 2 so that the second argument is
assumed to contain the coefficient controls.
optimize—527

Optimization Options
grads=integer Specifies an argument number corresponding to analytic
gradients for each of the coefficients. If this option is not
specified, gradients are evaluated numerically.
Available for “ls” and “ml” estimation.
• If the objective argument is a scalar, the gradient
argument should be a vector of length equal to the num-
ber of elements in the coefficient argument.
• If the objective argument is a series, the gradient
argument should be a group object containing one series
per element of the coefficient argument. The series obser-
vations should contain the corresponding derivatives for
each observation in the current workfile sample.
• For a vector objective, the gradient argument should
be a matrix with number of rows equal to the length of
the objective vector, and columns equal to the number of
elements in the coefficient argument.
• “grad=” may not be specified if the objective is a
matrix.
hess=arg Specify the type of Hessian approximation: “numeric”
(numerical approximation), “bfgs” (Broyden–Fletcher–
Goldfarb–Shanno), or “opg” (outer product of gradients, or
BHHH).
“opg” is only available when using “ls” or “ml” optimiza-
tion. The default value is “bfgs” unless using “ls” optimiza-
tion, which defaults to “opg”.
step=arg Set the step method: “marquardt”, “dogleg” or “line-
(default_= search”.
“marquardt”)
scale=arg Set the scaling method: “maxcurve” (default), or “none”.
m=int Set the maximum number of iterations
c=number Set the convergence criteria.
trust=number Sets the initial trust region size as a proportion of the initial
(default=0.25) control values.
Smaller values of this parameter may be used to provide a
more cautious start to the optimization in cases where
larger steps immediately lead into an undesirable region of
the objective.
Larger values may be used to reduce the iteration count in
cases where the objective is well behaved but the initial
values may be far from the optimum values.
528—Chapter 17.Command Reference

deriv=high Always use high precision numerical derivatives. Without


this option, EViews will start by using lower precision
derivatives, and switch to higher precision as the optimiza-
tion progresses.
feps=number Set the expected relative accuracy of the objective function.
(default=2.2e-16) The value indicates what fraction of the observed objective
value should be considered to be random noise.
noerr Turn off error reporting.
finalh=name Save the final Hessian matrix into the workfile with name
name.
For “hess=bfgs”, the final Hessian will be based on
numeric derivatives rather than the BFGS approximation
used during the optimization since the BFGS approxima-
tion need not converge to the true Hessian.

Examples
The first example estimates a regression model using maximum likelihood. The subroutine
LOGLIKE first computes the regression residuals using the coefficients in the vector BETA
along with the dependent variable series given by DEP and the regressors in the group
REGS.
subroutine loglike(series logl, vector beta, series dep, group regs)
series r = dep - beta(1) - beta(2)*regs(1) - beta(3)*regs(2) -
beta(4)*regs(3)
logl = @log((1/beta(5))*@dnorm(r/beta(5)))
endsub

series LL
vector(5) MLCoefs
MLCoefs = 1
MLCoefs(5) = 100
optimize(ml=1, finalh=mlhess, hess=numeric) loglike(LL, MLCoefs, y,
xs)

The optimize command instructs EViews to use the LOGLIKE subroutine for purposes of
maximization, and to use maximum likelihood to maximize the sum (over the workfile sam-
ple) of the LL series with respect to the five elements of the vector MLCOEFS. EViews
employs a numeric approximation to the Hessian in optimization, and saves the final esti-
mate in the workfile in the sym object MLHESS.

Notice that we specify initial values for the MLCOEFS coefficients prior to calling the optimi-
zation routine.
optimize—529

Our second example recasts the estimation above as a least squares optimization problem,
and illustrates the use of the “grads=” option to employ analytically computed gradients
defined in the subroutine.
subroutine leastsquareswithgrads(series r, vector beta, group grads,
series dep, group regs)
r = dep - beta(1) - beta(2)*regs(1) - beta(3)*regs(2) -
beta(4)*regs(3)
grads(1) = 1
grads(2) = regs(1)
grads(3) = regs(2)
grads(4) = regs(3)
endsub

series LSresid
vector(4) LSCoefs
lscoefs = 1
series grads1
series grads2
series grads3
series grads4
group grads grads1 grads2 grads3 grads4
optimize(ls=1, grads=3) leastsquareswithgrads(LSresid, lscoefs,
grads, y, xs)

Note that for a linear least squares problem, the derivatives of the coefficients are trivial -
the regressors themselves (and a series of ones for the constant).

The next example uses matrix computation to obtain an optimizer objective that finds the
solution to the same least squares problem. While the optimizer is not a solver, we can trick
it into solving that equation by creating a vector of residuals equal to  XX b – XY , and
asking the optimizer to find the values of b that minimize the square of those residuals:
subroutine local matrixsolve(vector rvec, vector beta, series dep,
group regs)
stom(regs, xmat)
xmat = @hcat(@ones(100), xmat)
stom(dep, yvec)
rvec = @transpose(xmat)*xmat*beta - @transpose(xmat)*yvec
rvec = @epow(rvec,2)
endsub
vector(4) MSCoefs
MSCoefs = 1
vector(4) rvec
optimize(min=1) matrixsolve(rvec, mscoefs, y, xs)
530—Chapter 17.Command Reference

The first few lines of the subroutine convert the input dependent variable series and regres-
sor group into matrices. Note that the regressor group does not contain a constant term
upon input, so we append a column of ones to the regression matrix XMAT, using the @hcat
command.

Lastly, we define a subroutine containing the quadratic form, and use the optimize com-
mand to find the value that minimizes the function:
subroutine f(scalar !y, scalar !x)
!y = 5*!x^2 - 3*!x - 2
endsub
scalar in = 0
scalar out = 0
optimize(min) f(out, in)

The subroutine F calculates the simple quadratic formula:


2
Y  5X – 3X – 2 (17.1)

which attains a minimum of -2.45 at an IN value of 0.3.

Cross-references
For discussion, see Chapter 10. “User-Defined Optimization,” beginning on page 261.

optsave Object Container, Data, and File Commands

Save the current EViews global options settings “.INI” files into a directory.

Syntax
optsave directory

Save a copy of the current global options settings into the specified directory. Usually this
command will be used in conjuncture with a later use of the optset command. Any exist-
ing option settings in the directory will be overwritten.

“General Options” and “Graphics Defaults” will always be saved. “Database registry set-
tings” and “Database object aliases” will only be saved if the file location setting for the
“Database Registry” and “Alias Map Path” is the same as the file location of the INI File
Path.

If the directory name is omitted, the option settings currently in effect will be used to replace
the default global options. (This can be used to copy option settings back into your default
settings after the optset command has switched to using options in a different directory).
optset—531

Note that this command does not change which set of options are active. You must follow
this command with the optset command if you would like to switch to using the saved
copy as your active set of options.

Cross-references
See Appendix A. “Global Options,” beginning on page 2539 of User’s Guide I for discussion
of the global options.

See also optset (p. 531).

optset Object Container, Data, and File Commands

Replace the current EViews global options settings “.INI” files with ones based in a differ-
ent directory.

Syntax
optset directory

Temporarily switch to using the global options settings stored within “.INI” files in the spec-
ified directory. These will typically have been previously saved by using the optsave com-
mand.

“General Options” and “Graphics Defaults” will always be switched. “Database registry set-
tings” and Database object aliases” will only be switched if the file location setting for the
“Database Registry” and “Alias Map Path” is the same as the file location of the INI File
Path.

The new options will stay in effect until EViews is restarted or until the optset command is
executed again with a different directory. After the optset command has been issued,
changing settings using the Options menu will modify settings in the new directory.

If the directory name is omitted, the global options settings will be reset to use the settings
from the default location (the same as restarting EViews).

Note that you can use the command “optset .\” in a program to switch to using the
global options saved in the same directory as the program file. This can be used to ensure
that multiple users always use the same global options settings when running a shared pro-
gram.

Cross-references
See Appendix A. “Global Options,” beginning on page 2539 of User’s Guide I for discussion
of the global options.

See also optsave (p. 530).


532—Chapter 17.Command Reference

ordered Interactive Use Commands

Estimation of ordered dependent variable models.

Syntax
equation name.ordered(options) y x1 [x2 x3 ...]
equation name.ordered(options) specification

Options
d=arg Specify likelihood: normal likelihood function, ordered pro-
(default=“n”) bit (“n”), logistic likelihood function, ordered logit (“l”),
Type I extreme value likelihood function, ordered Gompit
(“x”).
optmethod = Optimization method: “bfgs” (BFGS); “newton” (Newton-
arg Raphson), “opg” or “bhhh” (OPG or BHHH), “legacy”
(EViews legacy).
Newton-Raphson is the default method.
optstep = arg Step method: “marquardt” (Marquardt); “dogleg” (Dog-
leg); “linesearch” (Line search).
Marquardt is the default method.
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method)., “glm” (GLM
method)..
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian).
(Applicable when non-legacy “optmethod=”.)
h Huber-White quasi-maximum likelihood (QML) standard
errors and covariances.
(Legacy option Applicable when “optmethod=legacy”).
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
s Use the current coefficient values in “C” as starting values
(see also param (p. 564)).
output—533

s=number Specify a number between zero and one to determine start-


ing values as a fraction of preliminary EViews default val-
ues (out of range values are set to “s=1”).
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print results.

If you choose to employ user specified starting values, the parameters corresponding to the
limit points must be in ascending order.

Examples
ordered(d=l,cov=huber) y c wage edu kids

estimates an ordered logit model of Y on a constant, WAGE, EDU, and KIDS with QML stan-
dard errors. This command uses the default quadratic hill climbing algorithm.
param c(1) .1 c(2) .2 c(3) .3 c(4) .4 c(5).5
equation eq1.binary(s) y c x z
coef betahat = @coefs

estimates an ordered probit model of Y on a constant, X, and Z from the specified starting
values. The estimated coefficients are then stored in the coefficient vector BETAHAT.

Cross-references
See “Ordered Dependent Variable Models” on page 1450 of the User’s Guide II for additional
discussion.

See also binary (p. 382).

See Equation::ordered (p. 210) for the equivalent equation object command.

output Programming Commands

Redirect printer output.

You may specify that any procedure that would normally send output to the printer puts out-
put in a text, Rich Text Format (RTF), or comma-separated value (CSV) file, in a spool
object, or into frozen table or graph objects in the current workfile.
534—Chapter 17.Command Reference

Syntax
output base_name
output(f) base_name
output(options) [path\]file_name
output(s) spool_name
output off

By default, the output command redirects the output into frozen objects. You should supply
a base name after the output keyword. Each subsequent print command will create a new
table or graph object in the current workfile, using the base name and an identifying num-
ber. For example, if you supply the base name of “OUT”, the first print command will gener-
ate a table or graph named OUT01, the second print command will generate OUT02, and so
on.

You can also use the optional settings, described below, to redirect table and text output to a
text, RTF, or CSV file, or all output (including graphs) to an RTF file. If you elect to redirect
output to a file, you must specify a filename.

You can use the “s” option, described below, to redirect all output to a spool object.

When followed by the optional keyword off, the output command turns off output redirec-
tion. Subsequent print commands will be directed to the printer.

Options
f Redirect all output to frozen objects in the default workfile,
using base_name.
t Redirect table and text output to a text file. Graphic output
will still be sent to the printer.
r Redirect all output to an Rich Text Format (RTF) file.
v Redirect all output to an comma-separated value (CSV) file.
output—535

s Redirect all output to a spool object.


o Overwrite file if necessary. If the specified filename for the
text, RTF, or CSV file exists, overwrite the file. The default
is to append to the file.
Only Applicable when text, RTF, or CSV file output (speci-
fied using options “t”, “r”, or “v”).
c Command logging. Output both the output, and the com-
mand used to generate the output.
This option is only applicable in a program when used in
conjunction with the pon (p. 351) command which
enables automatic printing of output. The use of pon is not
required when output is specified in a command window.
Only Applicable when text, RTF, or CSV file output (speci-
fied using options “t”, “r”, or “v”).

Examples
output print_

causes the first print command to generate a table or graph object named PRINT_01, the sec-
ond print command to generate an object named PRINT_02, and so on.
output(t) c:\data\results
equation eq1.ls(p) log(gdp) c log(k) log(l)
eq1.resids(g,p)
output off

The first line redirects printing to the RESULTS.TXT file, while the print option of the second
and third lines sends the graph output to the printer. The last line turns output redirection
off and restores normal printer use.

If instead, the first line read:


output(r) c:\data\results

all subsequent output would be sent to the RTF file RESULTS.RTF.


output(s) mySpool

redirects all output to the MYSPOOL spool. If the spool already exists, printed objects will be
appended to the end of the spool.

Cross-references
See “Print Setup,” beginning on page 2562 of User’s Guide I for further discussion.

See also pon (p. 351), poff (p. 350).


536—Chapter 17.Command Reference

pageappend Object Container, Data, and File Commands

Append contents of the specified workfile page to the active workfile page.

Syntax
pageappend(options) wfname[\pgname] [object_list]

where wfname is the name of a workfile that is currently in memory. You may optionally
provide the name of a page in wfname that you wish to used as a source, and the list of
objects to be read from the source workfile page. If no wfname is provided, EViews will use
the default page in the source workfile.

The command appends the contents of the source page to the active page in the default
workfile. The target page is first unstructured (if necessary) and its range is expanded to
encompass the combined range of the sample from the source workfile page, and the desti-
nation page.

The default behavior is to append all series and alpha objects (but not other types) from the
source page, but the optional object_list may be provided to specify specific series, or to
specify objects other than series or alpha objects to be included. Command options may also
be used to modify the list of objects to be included.

Note that since this operation is performed in place, the original workfile page cannot be
recovered. We recommend that you consider backing up your original page using pagecopy
(p. 538).

Options
smpl=smpl_spec Specifies an optional sample identifying which observa-
tions from the source page are to be appended. Either pro-
vide the sample range in double quotes or specify a named
sample object. The default is “@all”.
allobj Specifies that all objects (including non-series and non-
alpha objects) should be appended. For objects other than
series and alphas, appending involves simply copying the
objects from the source page to the destination page. This
option may not be used with an explicit object_list specifi-
cation.
match Specifies that only series and alphas in the append page
that match series and alphas of the same name in the
active page should be appended. This option may not be
used with “allobj” or with an explicit object_list specifica-
tion.
pagecontract—537

sufix=suffix_arg Specifies a string to be added to the end of the source


(default=“_a”) object name, if necessary, to avoid name collision when
creating a new object in the target page.
obsid=arg Provides the name of a series used to hold the date or
observation ID of each observation in the destination work-
file.
wfid=arg Provides the name of a (boolean) series to hold an indica-
tor of the source for each observation in the destination
workfile (0, if from the destination; 1, if from the source).

Examples
pageappend updates

appends, to the default workfile page, all of observations in all of the series in the active
page of the workfile UPDATES.
pageappend(match, smpl="1999 2003") updates

restricts the series to those which match (by name) those in the default workfile page, and
restricts the observations to merge to those between 1999 and 2003.
pageappend newdat\page1 income cons

takes only the INCOME and CONS series from the PAGE1 of the NEWDATA workfile, and
appends them to the current workfile page.
pageappend(alltypes, suffix="_1") mydata

appends all objects from MYDATA, merging series with matching names, and renaming
other matching objects by appending “_1” to the end of the name.

Cross-references
See “Appending to a Workfile” on page 307 of User’s Guide I for discussion.

See also pagecopy (p. 538).

pagecontract Object Container, Data, and File Commands

Contract the active workfile page according to the specified sample.

Syntax
pagecontract smpl_spec

where smpl_spec is a sample specification. Contraction removes observations not in speci-


fied sample from the active workfile page. Note that since this operation is performed in
538—Chapter 17.Command Reference

place, you may wish to backup your original page (see pagecopy (p. 538)) prior to contract-
ing.

Examples
pagecontract if income<50000 and race=2

removes all observations with INCOME values greater than or equal to 50000 and RACE not
equal to 2.
pagecontract 1920 1940 1945 2000

removes observations for the years 1941 to 1944.

Cross-references
See “Contracting a Workfile” on page 310 of User’s Guide I for discussion.

See also pagecopy (p. 538).

pagecopy Object Container, Data, and File Commands

Copies all or part of the active workfile page to a new workfile, or to a new page within the
default workfile.

Syntax
pagecopy(options) [object_list]

where the optional object_list specifies the workfile objects to be copied. If object_list is not
provided, all objects will be copied subject to the option restrictions discussed below.

If copying objects to a new page within the default workfile, you may choose to copy series
objects (series, alphas, and links) by value or by link (by employing the “bylink” option). If
you elect to copy by value, links in the source page will converted to ordinary series and
alpha objects when they are copied. If you copy by link, series and alpha objects in the
source page are converted to links when copied. The default is to copy by value.

If you copy objects to a new workfile, data objects must be copied by value.
pagecopy—539

Options
bylink Specifies that series and alpha objects be copied as links to
the source page. This option is not available if you use the
“wf=” option, since linking requires that the destination
page be in the same workfile as the source page. Automati-
cally sets the “dataonly” option so that only series, alphas,
links, and valmaps will be copied.
smpl=smpl_spec Specifies an optional sample identifying which observa-
tions from the source page are to be appended. Either pro-
vide the sample range in double quotes or specify a named
sample object. The default is “@all”.
rndobs=integer Copy only a random subsample of integer observations
from the specified sample. Not available with “bylink,”
“rndpct,” or “prob.”
rndpct=arg Copy only a random percentage subsample of arg (a num-
ber between 0 and 100) of the specified sample. Not avail-
able with “bylink,” “rndobs,” or “prob.”
prob=arg Copies a random subsample where each observation has a
fixed probability, prob, of being selected. prob should be
entered as a percentage value (a number between 0 and
100). Not available with “bylink,” “rndobs,” or “rndpc”
dataonly Only series, alphas, links, and valmaps should be copied.
The default is to copy all objects (unless the “bylink”
option is specified, in which case only series objects are
copied).
nolinks Do not copy links from the source page.
wf=wf_name Optional name for the destination workfile. If not provided,
EViews will create a new untitled workfile. Not available if
copying using the “bylink” option.
page=page_name Optional name for the newly created page. If not provided,
EViews will use the next available name of the form “Unti-
tled##”, where ## is a number.

Examples
pagecopy(page=allvalue, wf=newwf)

will first create a new workfile named NEWWF, with a page ALLVALUE that has the same
structure as the current page. Next, all of the objects in the active workfile page will be cop-
ied into the new page, with the series objects copied by value. In contrast,
pagecopy(bylink, page=alllink)
540—Chapter 17.Command Reference

will instead create a page ALLLINK in the existing workfile, and will copy all series objects
by creating links in the new page.
pagecopy(page=partcopy, bylink, smpl="1950 2000 if
gender=""male""") a* *z

will create a new page named PARTCOPY in the existing workfile containing the specified
subsample of observations, and will copy all series objects in the current page beginning
with the letter “A” or ending with the letter “Z”. The objects will be copied by creating links
in the new page.
pagecopy(page=rndcopy, smpl="1950 2000 if gender=""male""",
rndobs=200, dataonly, nolinks)

creates a new workfile and page RNDCOPY containing a 200 observation random sample
from the specified subsample. Series and alpha objects only will be copied by value from the
source page.

Cross-references
See “Copying from a Workfile” on page 310 of User’s Guide I for discussion.

See also pageappend (p. 536).

pagecreate Object Container, Data, and File Commands

Create a new page in the default workfile. The new page becomes the active page.

Syntax
pagecreate(options) freq[(subperiod_opts)] start_date end_date [num_cross_sections]
pagecreate(options) u num_observations
pagecreate(id_method[,options]) id_list [@srcpage page_list]
pagecreate(idcross[,options]) id1 id2 [@srcpage page1 page2]
pagecreate(idcross[,options]) id1 @range(freq, start_date, end_date) [@srcpage
page1]

These different forms of the pagecreate command encompass three distinct approaches to
creating a new workfile page: (1) regular frequency description or unstructured data descrip-
tion; (2) using the union or intersection of unique values from one or more ID series in exist-
ing workfile pages; (3) using the cross of unique values from two identifier series or from an
identifier series and a date range. Each of these approaches is described in greater detail
below.
pagecreate—541

Regular Frequency or Unstructured Description


The first two forms of the command permit you to create a new workfile page using a regu-
lar frequency or unstructured description:
• pagecreate(options) freq[(subperiod_opts)] start_date end_date [num_cross_sections]
• pagecreate(options) u num_observations

The first form of the command should be employed to create a regular frequency page with
the specified frequency, start, and end date. If you include the optional argument
num_cross_sections, EViews will create a balanced panel page using integer identifiers for
each of the cross-sections. Note that more complex panel structures may be defined using
pagestruct (p. 558).

The second form of the command creates an unstructured workfile with the specified num-
ber of observations.

Note that these forms of the command are analogous to wfcreate (p. 634) except that
instead of creating a new workfile, we create a new page in the default workfile.

The freq argument should be specified using one of the following forms:
Sec[opt], 5Sec[opt], Seconds in intervals of: 1, 5, 15, or 30 seconds, respec-
15Sec[opt], tively. You may optionally specify days of the week and
30Sec[opt] start and end times during the day using the opt parameter.
See explanation of subperiod options below.
Min[opt], Minutes in intervals of: 1, 2, 5, 10, 15, 20, or 30 minutes,
2Min[opt], respectively. You may optionally specify days of the week
5Min[opt], and start and end times during the day using the opt
10Min[opt], parameter. See explanation of subperiod options below.
15Min[opt],
20Min[opt],
30Min[[opt]
H[opt], 2H[opt], Hours in intervals of: 1, 2, 4, 6, 8, or 12 hours, respectively.
4H[opt], 6H[opt], You may optionally specify days of the week and start and
8H[opt], 12H[[opt] end times during the day using the opt parameter. See
explanation of subperiod options below.
D(s, e) Daily with arbitrary days of the week. Specify the first and
last days of the week with integers s and e, where Monday
is given the number 1 and Sunday is given the number 7.
(Note that the “D” option used to specify a 5-day frequency
in versions prior to EViews 7).
D5 or 5 Daily with five days per week, Monday through Friday.
D7 or 7 Daily with seven days per week.
542—Chapter 17.Command Reference

W Weekly
T Ten-day (daily in intervals of ten).
F Fortnight
BM Bimonthly
M Monthly
Q Quarterly
S Semi-annual
A or Y Annual
2Y, 3Y, 4Y, 5Y, 6Y, Multi-year in intervals of: 2, 3, 4, 5, 6, 7, 8, 9, 10, or 20
7Y, 8Y, 9Y, 10Y, 20Y years, respectively.

Subperiod options
EViews allows for setting the days of the week and the time of day within intraday frequen-
cies, which include seconds, minutes, and hours. For instance, you may specify hourly data
between 8AM and 5PM on Monday through Wednesday. These subperiod options should
follow the frequency keyword and be enclosed in parentheses.

To specify days of the week, use integers to indicate the days, where Monday is given the
number 1 and Sunday is given the number 7. For example,
pagecreate(wf=strhours) 30MIN(1-6, 8:00-17:00) 1/3/2000 12/30/2000

indicates a half-hour frequency that includes Monday through Saturday from 8AM to 5PM.

To specify the start and end times, you may use either a 24 hour clock, including minutes
and optionally seconds, or a 12 hour clock using AM and PM. For example, each of the fol-
lowing represents 8PM: 8PM, 8:00PM, 8:00:00PM, 20:00, and 20:00:00. Thus, our previous
example could have been written:
pagecreate(wf=strhours) 30MIN(1-6, 8AM-5PM) 1/3/2000 12/30/2000

Note that day and time ranges may be delimited by either commas or dashes. So this com-
mand is also equivalent to:
pagecreate(wf=strhours) 30MIN(1,6, 8AM,5PM) 1/3/2000 12/30/2000

though you will likely find the dashes easier to read.

If you wish to include all days of the week but would like to specify a start and end time, set
the date range to include all days and then specify the times. The day of the week parameter
appears first and is required if you wish to supply the time of day parameters. For instance,
pagecreate(wf=storehours) 30MIN(1-7, 10AM-3PM) 1/3/2000 12/30/2000

indicates a half-hour frequency from 10AM to 3PM on all days of the week.
pagecreate—543

You may also include a time with the start and end date parameters to specify partial days at
the beginning or end of the workfile. For example,
pagecreate(wf=strhours) 30MIN(1-6, 8AM-5PM) 1/3/2000 10AM
12/30/2000 2PM

creates the same workfile page as above, but limits the first day, 1/3/2000, to 10AM - 5PM
and the last day, 12/30/2000, to 8AM - 2PM.
Unique Values from a Set of Identifier Series
The next form of the command allows for creating pages from the unique values of one or
more identifier series found in one or more workfile pages:
• pagecreate(id_method[,options]) identifier_list [@srcpage page_list]

The identifier_list should include one or more ID series. If more than one ID series is pro-
vided, EViews will use the values that are unique across all of the series. If you wish to cre-
ate a page with a date structure, you should specify one of your identifiers using the special
“@DATE” keyword identifier, enclosing the series (or the date ID component series) inside
parentheses. If you wish to use the date ID values from the source workfile page, you may
use the “@DATE” keyword without arguments.

The id_method describes how to handle unique ID values that differ across multiple pages:
id Use the observed values of the series in the identifier_list in
specified page.
idunion Use the union of the observed values of the series in the
identifier_list in the specified pages.
idintersect Use the intersection of the observed values of the series in
the identifier_list in the specified pages.

If the optional source page or list of source pages is not provided, EViews will use the
default workfile page. Note that if a single workfile page is used, the two ID methods yield
identical results.
Cross of Unique Values from Two Identifier Series or from an Identifier Series and a Date Range
The last two forms of the command create a new page by crossing the unique values in two
ID series located in one or more pages, or by crossing an ID series from one page with a date
range. First, you may specify a pair of identifiers, and optionally source pages where they
are located,
• pagecreate(idcross[,options]) id1 id2 [@srcpage page1 page2]

You may instruct EViews to create a date structured page by specifying one of your two iden-
tifiers using a “@DATE” specification as described above.
544—Chapter 17.Command Reference

Alternately, you may provide a single identifier and a range specification using the
“@RANGE” keyword with a freq, start_date, and end_date, and optionally, the location of
the identifier series.
• pagecreate(idcross[,options]) id1 @range(freq, start_date, end_date) [@srcpage
page1]

Options
smpl=smpl_spec Specifies an optional sample identifying which observa-
tions to use when creating a page using the id_method
option. Either provide the sample range in double quotes or
specify a named sample object. The default is “@all”.
When multiple source workfiles are involved, the specified
sample must be valid for all workfiles.
page=page_name Optional name for the newly created page. If not provided,
EViews will use the next available name of the form “Unti-
tled##”, where ## is a number.
wf=wf_name Optional name for the new workfile. If not provided,
EViews will create a new page in the default workfile.
prompt Force the dialog to appear from within a program.

Examples
Regular Frequency or Unstructured Description
The two commands:
pagecreate(page=annual) a 1950 2005
pagecreate(page=unstruct) u 1000

create new pages in the existing workfile. The first page is an annual page named ANNUAL,
containing data from 1950 to 2005; the second is a 1000 observation unstructured page
named UNSTRUCT.
pagecreate(page=mypanel) a 1935 1954 10

creates a new workfile page named MYPANEL, containing a 10 cross-section annual panel
for the years 1935 to 1954.
pagecreate(page=fourday) D(1,4) 1/3/2000 12/31/2000

specifies a daily workfile page from January 3, 2000 to December 31, 2000, including only
Monday through Thursday. The day range may be delimited by either a comma or a dash,
such that
pagecreate(wf=fourday) D(1-4) 1/3/2000 12/31/2000

is equivalent to the previous command.


pagecreate—545

pagecreate(wf=captimes) 15SEC(2-4) 1/3/2000 12/30/2000

creates a workfile page with 15 second intervals on Tuesday through Thursday only, from
1/3/2000 to 12/30/2000.
Unique Values from a Set of Identifier Series
pagecreate(id, page=statepage) state

creates a new page STATEIND using the distinct values of STATE in the current workfile
page.
pagecreate(id, page=statepage) state industry

creates a new page named STATEIND, using the distinct STATE/INDUSTRY values in the
active page.
pagecreate(id, page=stateyear) state @date(year)
pagecreate(id, page=statemonth) @date(year, month)

use STATE, along with YEAR, and the YEAR and MONTH series respectively, to form identi-
fiers that will be used in creating the new dated workfile pages.
pagecreate(id, smpl="if sex=1") crossid @date

creates a new page using CROSSID and existing date ID values of the active workfile page.
Note that only observations in the subsample defined by “@all if sex=1” are used to deter-
mine the unique values.
pagecreate(id, page=AllStates, smpl="if sex=""Female""") stateid
@srcpage north south east west

creates a new page ALLSTATES structured using the union of the unique values of STATEID
from the NORTH, SOUTH, EAST and WEST workfile pages that are in the sample “if
sex="Female"”. Note the use of the double quote escape character for the double quotes in
the sample string.
pagecreate(idintersect, page=CommonStates, smpl="1950 2005")
stateid @srcpage page1 page2 page3

creates a new page name COMMONSTATES structured using the intersection of the unique
values of STATEID taken from the pages PAGE1, PAGE2, and PAGE3.
Cross of Unique Values from Two Identifier Series or from an Identifier Series and a Date Range
pagecreate(idcross,page=UndatedPanel) id1 id2 @srcpage page1 page2

will add the new page UNDATEDPANEL to the current workfile. UNDATEDPANEL will be
structured as an undated panel using values from the cross of ID1 from PAGE1 and ID2 from
PAGE2.

To create a dated page using the “idcross” option, you must tag one of the identifiers using
an “@DATE” specification:
546—Chapter 17.Command Reference

pagecreate(idcross,page=AnnualPanel) id1 @date(year) @srcpage


page1 page2

You may also specify the cross of an identifier with a date range:
pagecreate(idcross,page=QuarterlyPanel) id1 @range(q, 1950, 2006)
@srcpage page1

creates a quarterly panel page named QUARTERLYPANEL using the cross of ID1 taken from
PAGE1, and quarterly observations from 1950q1 to 2006q4.

Cross-references
See “Creating a Workfile,” on page 30 of User’s Guide I for discussion.

See also wfcreate (p. 634) and pagedelete (p. 546).

pagedelete Object Container, Data, and File Commands

Delete the named pages from the default workfile.

Syntax
pagedelete [pgname1 pgname2 pgname3...]

By default pagedelete will delete the currently active page in the default workfile. You may
specify other pages to delete by listing them, in a space delimited list, after the pagedelete
command.

Examples
pagedelete page1 page2

Cross-references
See also pagecreate (p. 540).

pageload Object Container, Data, and File Commands

Load one or more new pages in the default workfile.

Syntax
pageload [path\]workfile_name [page1] [page2] [...]
pageload(options) source_description [@keep keep_list] [@drop drop_list] [@keep-
map keepmap_list] [@dropmap dropmap_list] [@selectif condition]
pageload(options)source_description table_description [@keep keep_list] [@drop
drop_list] [@keepmap keepmap_list] [@dropmap dropmap_list] [@selectif con-
dition]
pagerefresh—547

The basic syntax for pageload follows that of wfopen (p. 640). The difference between the
two commands is that pageload creates a new page in the default workfile, rather than open-
ing or creating a new workfile. If a page is loaded with a name that matches an existing
page, EViews will rename the new page to the next available name (e.g., “INDIVID” will be
renamed “INDIVID1”.

If a workfile is provided as the source file, EViews will, by default, open all pages in the
source workfile. Specific pages may be loaded by providing their names.

Examples
pageload "c:\my documents\data\panel1"

loads the workfile PANEL1.WF1 from the specified directory. All of the pages in the workfile
will be loaded as new pages into the current workfile.
pageload f.wf1 mypage

loads the page “mypage” in the workfile F.WF1 located in the default directory.

See the extensive set of examples in wfopen (p. 640).

Cross-references
See “Creating a Page by Loading a Workfile or Data Source” on page 78 of User’s Guide I for
discussion.

See also wfopen (p. 640) and pagecreate (p. 540).

pagerefresh Object Container, Data, and File Commands

Refresh all links and auto-series in the active workfile page. Primarily used to refresh links
that use external database data.

Syntax
pagerefresh

Cross-references
See also Chapter 8. “Series Links,” on page 249 of User’s Guide I for a description of link
objects, and “Auto-Updating Series” on page 219 of User’s Guide I for a discussion of auto-
updating series.

See wfrefresh (p. 656) to reference an entire workfile.

See also Link::link (p. 530) and Link::linkto (p. 530) in the Object Reference.
548—Chapter 17.Command Reference

pagerename Object Container, Data, and File Commands

Rename the specified workfile page.

Syntax
pagerename old_name new_name

renames the old_name page in the default workfile to new_name. Page names are case-
insensitive for purposes of comparison, even though they are displayed using the input case.

Examples
pagerename Page1 StateByYear

Cross-references
See also pagecreate (p. 540).

pagesave Object Container, Data, and File Commands

Save the active page in the default workfile as an EViews workfile (.WF1 file) or as a for-
eign data source.

Syntax
pagesave(options) [path\]filename
pagesave(options) source_description [nonames] [@keep keep_list] [@drop drop_list]
[@keepmap keepmap_list] [@dropmap dropmap_list] [@smpl smpl_spec]
pagesave(options) source_description table_description [nonames] [@keep keep_list]
[@drop drop_list] [@keepmap keepmap_list] [@dropmap dropmap_list]
[@smpl smpl_spec]

The command saves the active page in the specified directory using filename. By default, the
page is saved as an EViews workfile, but options may be used to save all or part of the page
in a foreign file or data source.

When saving to a foreign data file, the basic specification consists of a “type=” option and
source_description and table_description arguments which specify the format of the foreign
data file. See below for details on source_description and table_description.

The remaining optional elements specify the actual elements to be saved.


pagesave—549

Options
type=arg, t=arg Optional type specification: (see table below).
ODBC support is not provided in EViews Standard Edition.
mode=arg Specify whether to create a new file, overwrite an existing
file, or update an existing file. arg may be “create” (create
new file only; error on attempt to overwrite) or “update”
(update an existing file, only overwriting the area specified
by the range= table_description).
If a “mode=” option is not provided, EViews will create a
new file, unless the file already exists in which case it will
overwrite it.
Note that the “mode=update” option is only available for
Excel in 1) Excel versions through 2003, if Excel is
installed, and 2) Excel 2007 (xml). Note: Excel does not
need to be installed for Excel 2007 writing.
maptype=arg Write selected maps as: numeric (“n”), character (“c”),
both numeric and character (“b”).
nomapval Do not write mapped values for series with attached value
labels (the default is to write mapped values)
noid Do not write observation identifiers to foreign data files (by
default, EViews will include a column with the date or
observation identifier).
nonames Do not write variable names (only application to file for-
mats that support writing raw data without variable
names). Only available in EViews 12 and later. EViews 11
and older should use nonames as an argument after the
output file name.
attr Include object attributes (if the output type supports it).
When specified, the first column will contain attribute
names and each attribute value will be displayed after the
name row.
550—Chapter 17.Command Reference

Excel Options
mode=arg Specify whether to create a new file, overwrite an existing
file, or update an existing file. arg may be “create” (create
new file only; error on attempt to overwrite) or “update”
(update an existing file, only overwriting the area specified
by the range= table_description).
If the “mode=” option is not used, EViews will create a
new file, unless the file already exists in which case it will
overwrite it.
Note that the “mode=update” option is only available for
Excel in 1) Excel versions through 2003, if Excel is
installed, and 2) Excel 2007 (xml). Note: Excel does not
need to be installed for Excel 2007 writing.

Excel 2007 Options


mode=arg Specify whether to create a new file, overwrite an existing
file, or update an existing file. arg may be “create” (create
new file only; error on attempt to overwrite) or “update”
(update an existing file, only overwriting the area specified
by the range= table_description).
If the “mode=” option is not used, EViews will create a
new file, unless the file already exists in which case it will
overwrite it.
Note that the “mode=update” option is only available for
Excel in 1) Excel versions through 2003, if Excel is
installed, and 2) Excel 2007 (xml). Note: Excel does not
need to be installed for Excel 2007 writing.
cellfmt=arg Specify whether to use EViews, pre-existing, or remove cell
formatting (colors, font, number formatting when possible,
column widths and row heights) for the written range.
arg may be “eviews” (replace current formatting in the file
with the same cell formatting in EViews), “preserve” (leave
current cell formatting already in the Excel file), or “clear”
(remove current formatting and do not replace).
strlen=arg Specify the maximum the number of characters written for
(default = 256) cells containing text. Strings in cells which are longer the
max, will be truncated.

The following table summaries the various foreign formats, along with the corresponding
“type=” keywords:
pagesave—551

Type Keywords Supports Attributes


Access “access”
Aremos-TSD “a”, “aremos”, “tsd”
Binary “binary”
dBASE “dbase”
Excel (through 2003) “excel” Yes
Excel 2007 (xml) “excelxml” Yes
EViews Workfile ---
Gauss Dataset “gauss”
GiveWin/PcGive “g”, “give”
HTML “html”
JSON** json
Lotus 1-2-3 “lotus”
ODBC Dsn File “dsn”
ODBC Data Source “odbc”
MicroTSP Workfile “dos”, “microtsp”
MicroTSP Mac Workfile “mac”
RATS 4.x “r”, “rats”
RATS Portable / TROLL “l”, “trl”
SAS Program “sasprog”
SAS Transport “sasxport”
SPSS “spss”
SPSS Portable “spssport”
Stata (Version 7 Format) “stata”
Tableau Data Extract “tde”
Text / ASCII “text” Yes
TSP Portable “t”, “tsp”

Note that if you wish to save your Excel 2007 XML file with macros enabled, you should
specify the explicit filename extension “.XLSM”.
Foreign Data Descriptions
When saving to a foreign data format the base specification consists of a basic specification
of source_description and table_description which specify the exact details of the format.
552—Chapter 17.Command Reference

The command for saving as foreign data formats is


pagesave(options) source_description [table_description] [@keep keep_list] [@drop
drop_list] [@keepmap keepmap_list] [@dropmap dropmap_list] [@smpl
smpl_spec] [nonames]

where the syntax of the table_description and variables_description differs slightly depend-
ing on the type of file.
• @keep, @drop, @keepmap, @dropmap, and @smpl arguments may be used to con-
trol what objects and observations to write.
• The nonames keyword may be used to suppress the writing of variable names in file
formats that support writing raw data without variable names.
• Note that the JSON type will ignore any @keep, @drop, and @smpl arguments.

Excel Files
The base syntax for writing Excel files is:
pagesave(options) source_description [table_description]

where source_description is the path and name of the Excel file to be saved, and where the
following table_description elements may be employed:
• “range = arg”, where arg is a range of cells to read from the Excel workbook, follow-
ing the standard Excel format [worksheet!][topleft_cell[:bottomright_cell]].
If the worksheet name contains spaces, it should be placed in single quotes. If the
worksheet name is omitted, the cell range is assumed to refer to the currently active
sheet. If only a top left cell is provided, a bottom right cell will be chosen automati-
cally to cover the range of non-empty cells adjacent to the specified top left cell. If
only a sheet name is provided, the first set of non-empty cells in the top left corner of
the chosen worksheet will be selected automatically. As an alternative to specifying
an explicit range, a name which has been defined inside the excel workbook to refer
to a range or cell may be used to specify the cells to read.
• “byrow”, transpose the incoming data. This option allows you to read files where the
series are contained in rows (one row per series) rather than columns.

Examples
HTML Files
The base syntax for saving HTML files is:
pagesave(options) source_description [table_description]

where source_description is the path and name of the file to be saved, and where the follow-
ing table_description element may be employed:
pagesave—553

• “byrow”, transpose the data. This option allows you to write files where the series are
contained in rows (one row per series) rather than columns.

Text and Binary and Other Files


The base syntax for saving other files is:
pagesave(options) source_description

where source_description is the path and name of the file to be saved.

Examples
EViews Workfile Examples
pagesave new_wf

saves the current EViews workfile page as “New_wf.WF1” in the default directory.
pagesave "c:\documents and settings\my data\consump"

saves the current workfile page as “Consump.WF1” in the specified path.


pagesave macro @keep gdp unemp

saves the two series GDP and UNEMP in a separate workfile, “macro.WF1” in the default
directory.
pagesave macro @dropmap gdp*

saves all of the series in the current workfile, other than those that match the name pattern
“gdp*” in a workfile, “macro.WF1” in the default directory.

The command:
pagesave "<mydropboxdrive>"\folder\nipa.wf1"

will save the file to the cloud location MYDROPBOXDRIVE.


Foreign Data Examples
pagesave(type=excelxml, mode=update) macro.xlsx

saves the current workfile page as a modern Excel “.XLSX” file.


pagesave(type=excelxml, mode=update) macro.xlsx range="Sheet2!a1"
byrow @keep gdp unemp

will save the two series GDP and UNEMP into the existing Excel file “macro.XLSX”, specify-
ing that the series should be written by row, starting in cell A1 on sheet Sheet2.

To save the latter file in a macro-enabled Excel 2007 file, you should specify the explicit file-
name extension “.XLSM”:
pagesave(type=excelxml, mode=update) macro.xlsm range="Sheet2!a1"
byrow @keep gdp unemp

Alternately,
554—Chapter 17.Command Reference

pagesave(type=excelxml, noid) macro.xlsx range="Sheet2!a1"

will save the current workfile page as the Excel file “macro.XLSX” but will not include a col-
umn of dates.

If you wish to save a column of dates in a specific date format, you can do so by first creat-
ing an alpha series in the workfile with the specified format, then saving the file with the
“noid” option including that alpha series:
alpha mydates = @datestr(@date, "YYYY-MM-DD")
pagesave(type=excelxml, noid) macro.xlsm range="Sheet2!a1" @keep
mydates gdp unemp

Will save the series GDP and UNEMP into the Excel file “macro.XLSM” along with a date
series with the format “YYYY-MM-DD”.

Cross-references
See “Saving a Workfile” on page 65 in the User’s Guide I.

See also wfopen (p. 640) and wfsave (p. 656).

pageselect Object Container, Data, and File Commands

Make the specified page in the default workfile the active page.

Syntax
pageselect pgname

where pgname is the name of a page in the default workfile.

Examples
pageselect page2

changes the active page to PAGE2.

Cross-references
See also wfselect (p. 663).

pagesort Object Container, Data, and File Commands

Sort the current workfile page.

The pagesort command sorts all series in the workfile page on the basis of the values of
one or more of the series. For purposes of sorting, NAs are considered to be smaller than any
pagestack—555

other value. By default, EViews will sort the series in ascending order. You may use options
to override the sort order.

EViews will first remove any workfile structures and then will sort the workfile using the
specified settings.

Syntax
pagesort(options) arg1 [arg2 arg3…]

List the name of the series or groups by which you wish to sort the workfile. If you list two
or more series, pagesort uses the values of the second series to resolve ties from the first
series, and values of the third series to resolve ties from the second, and so on.

Options
d sort in descending order.

Examples
pagesort(d) inc

sorts all series in the workfile in order of the INC series with the highest value of INC first.
NAs in INC (if any) will be placed at the bottom.
pagesort gender race wage

sorts all series in the workfile in order of the values of GENDER from low to high, with ties
resolved by ordering on the basis of RACE, with further ties resolved by ordering on the
basis of WAGE.

Cross-references
See “Sorting a Workfile” on page 331 of the User’s Guide I.

pagestack Object Container, Data, and File Commands

Create a panel structured workfile page using series, alphas, or links from the default
workfile page (convert repeated series to repeated observations).

Series in the new panel workfile may be created by stacking series, alphas, and links whose
names contain a pattern (series with names that differ only by a “stack identifier”), or by
repeating a single series, alpha, or link, for each value in a set of stack identifiers.

Syntax
pagestack(options) stack_id_list [@ series_to_stack]
pagestack(options) pool_name [@ series_to_stack]
pagestack(options) series_name_pattern [@ series_to_stack]
556—Chapter 17.Command Reference

The resulting panel workfile will use the identifiers specified in one of the three forms of the
command:
• stack_id_list includes a list of the ID values (e.g., “US UK JPN”).
• pool_name is the name of a pool object that contains the ID values.
• series_name_pattern contains an expression from which the ID values may be deter-
mined. The pattern should include the “?” character as a stand in for the parts of the
series names containing the stack identifiers. For example, if “CONS?” is the
series_name_pattern, EViews will find all series with names beginning with “CONS”
and will extract the IDs from the trailing parts of the observed names.

The series_to_stack list may contain two types of entries: stacked series (corresponding to
sets of series, alphas, and links whose names contain the stack IDs) and simple series (other
series, alphas, and links).

To stack a set of series whose names differ only by the stack IDs, you should enter an
expression that includes the “?” character in place of the IDs. You may list the names of a
single stacked series (e.g., “GDP?” or “?CONS”), or you may use expressions containing the
wildcard character “*” (e.g., “*?” and “?C*”) to specify multiple series.

By default, the stacked series will be named in the new workfile using the base portion of
the series name (if you specify “?CONS” the stacked series will be named “CONS”), and will
contain the values of the individual series stacked one on top of another. If one of the indi-
vidual series associated with a particular stack ID does not exist, the corresponding stacked
values will be assigned the value NA.

Individual (simple) series may also be stacked. You may list the names of individual simple
series (e.g., “POP INC”), or you can specify your series using expressions containing the
wildcard character “*” (e.g., “*”, “*C”, and “F*”). A simple series will be stacked on top of
itself, once for each ID value. If the target workfile page is in the same workfile, EViews will
create a link in the new page; otherwise, the stacked series will contain (repeated) copies of
the original values.

When evaluating wildcard expressions, stacked series take precedence over simple series.
This means that simple series wildcards will be processed using the list of series not already
included as a stacked series.

If the series_to_stack list is not specified, the expression “*? *”, is assumed.
pagestack—557

Options
?=name_patt, idre- Specifies the characters to use instead of the identifier, ”?”,
place = in naming the stacked series.
name_patt By default, the name_patt is blank, indicating, for exam-
ple, that the stacked series corresponding to the pattern
“GDP?” will be named “GDP” in the stacked workfile page.
If pattern is set to “STK”, the stacked series will be named
GDPSTK.
interleave Interleave the observations in the destination stacked
workfile (stack by using all of the series values for the first
source observation, followed by the values for the second
observation, and so on). The default is to stack observa-
tions by identifier (stack the series one on top of each
other).
wf=wf_name Optional name for the new workfile. If not provided,
EViews will create a new page in the default workfile.
page=page_name Optional name for the newly created page. If not provided,
EViews will use the next available name of the form “Unti-
tled##”, where ## is a number.

Examples
Consider a workfile that contains the seven series: GDPUS, GDPUK, GDPJPN, CONSUS,
CONSUK, CONSJPN, CONSFR, and WORLDGDP.
pagestack us uk jpn @ *?

creates a new, panel structured workfile page with the series GDP and CONS, containing the
stacked GDP? series (GDPUS, GDPUK, and GDPJPN) and stacked CONS? series (CONSUS,
CONSUK, and CONSJPN). Note that CONSFR and WORLDGDP will not be copied or
stacked.

We may specify the stacked series list explicitly. For example:


pagestack(page=stackctry) gdp? @ gdp? cons?

first determines the stack IDs from the names of series beginning with “GDP”, the stacks the
GDP? and CONS? series. Note that this latter example also names the new workfile page
STACKCTRY.

If we have a pool object, we may instruct EViews to use it to specify the IDs:
pagestack(wf=newwf, page=stackctry) countrypool @ gdp? cons?

Here, the panel structured page STACKCTRY will be created in the workfile NEWWF.
558—Chapter 17.Command Reference

Simple series may be specified by adding them to the stack list, either directly, or using wild-
card expressions. Both commands:
pagestack us uk jpn @ gdp? cons? worldgdp consfr
pagestack(wf=altwf) us uk jpn @ gdp? cons? *

stack the various GDP? and CONS? series on top of each other, and stack the simple series
GDPFR and WORLDGDP on top of themselves.

In the first case, we create a new panel structured page in the same workfile containing the
stacked series GDP and CONS and link objects CONSFR and WORLDGDP, which repeat the
values of the series. In the second case, the new panel page in the workfile ALTWF will con-
tain the stacked GDP and CONS, and series named CONSFR and WORLDGDP containing
repeated copies of the values of the series.

The following two commands are equivalent:


pagestack(wf=newwf) us uk jpn @ *? *
pagestack(wf=newwf) us uk jpn

Here, every series, alpha, and link in the source workfile is stacked and copied to the desti-
nation workfile, either by stacking different series containing the stack_id or by stacking
simple series on top of themselves.

The “?=” option may be used to prevent name collision.


pagestack(?="stk") us uk jpn @ gdp? gdp

stacks GDPUS, GDPUK and GDPJPN into a series called GDPSTK and repeats the values of
the simple series GDP in the destination series GDP.

Cross-references
For additional discussion, see “Stacking a Workfile” on page 323 in User’s Guide I. See also
pageunstack (p. 562).

pagestruct Object Container, Data, and File Commands

Assign a structure to the active workfile page.

Syntax
pagestruct(options) [id_list]
pagestruct(options) *

where id_list is an (optional) list of ID series. The “*” may be used as shorthand for the indi-
ces currently in place.
pagestruct—559

If an id_list is provided, EViews will attempt to auto determine the workfile structure. Auto-
determination may be overridden through the use of options.

If you do not provide an id_list, the workfile will be restructured as a regular frequency
workfile. In this case, either the “none” or the “freq=” and “start=” options described
below must be provided.

Options
none Remove the existing workfile structure.
freq= arg Specifies a regular frequency; if not provided EViews will
auto-determine the frequency. The frequency may be speci-
fied as “a” (annual), “s” (semi-annual), “q” (quarterly),
“m” (monthly), “w” (weekly), “d” (5-day daily), “7” (7-
day daily), or “u” (unstructured/undated).
start=arg Start date of the regular frequency structure; if not speci-
fied, defaults to “@FIRST”. Legal values for arg are
described below.
end=arg End date of the regular frequency structure; if not specified,
defaults to “@LAST”. Legal values for arg are described
below.
regular, reg When used with a date ID, this option informs EViews to
insert observations (if necessary) to remove gaps in the
date series so that it follows the regular frequency calendar.
The option has no effect unless a date index is specified.
create Allow creation of a new series to serve as an additional ID
series when duplicate ID values are found in any group.
EViews will use this new series as the observation ID.
The default is to prompt in interactive mode and to fail in
programs.
560—Chapter 17.Command Reference

balance=arg, Balance option (for panel data) describing how EViews


bal=arg should handle data that are unbalanced across ID (cross-
section) groups.
The arg should be formed using a combination of starts
(“s”), ends (“e”), and middles (“m”), as in “balance=se”
or “balance=m”.
If balancing starts (arg contains “s”), EViews will (if neces-
sary) add observations to your workfile so that each cross-
section begins at the same observation (the earliest date or
observation observed).
If balancing ends (arg contains “e”), EViews will add any
observations required so that each cross-section ends at the
same point (the last date or observation observed).
If balancing middles (arg contains “m”) EViews will add
observations to ensure that each cross-section has consecu-
tive observations from the earliest date or observation for
the cross-section to the last date or observation for the
cross-section.
Note that “balance=m” is implied by the “regular” option.
dropna Specifies that observations which contain missing values
(NAs or blank strings) in any ID series (including the date
or observation ID) be removed from the workfile. If “dro-
pna” is not specified and NAs are found, EViews will
prompt in interactive mode and fail in programs.
dropbad Specifies that observations for which any of the date index
series contain values that do not represent dates be
removed from the workfile. If “dropbad” is not provided
and bad dates are present, EViews will prompt in interac-
tive mode and fail in programs.

The values for start and end dates should contain date literals (actual dates or periods), e.g.,
“1950q1” and “2/10/1951”, “@FIRST”, or “@LAST” (first and last observed dates in the
date ID series). Date literals must be used for the “start=” option when restructuring to a
regular frequency.

In addition, offsets from these date specifications can be specified with a “+” or “–” fol-
lowed by an integer: “@FIRST-5”, “@LAST+2”, “1950m12+6”. Offsets are most often used
when resizing the workfile to add or remove observations from the endpoints.

Examples
pagestruct state industry

structures the workfile using the IDs in the STATE and INDUSTRY series.
pageunlink—561

A date ID series (or a series used to form a date ID) should be tagged using the “@DATE”
keyword. For example:
pagestruct state @date(year)
pagestruct(regular) @date(year, month)

A “*” may be used to indicate the indices defined in the current workfile structure.
pagestruct(end=@last+5) *

adds 5 observations to the end of the current workfile.

When you omit the id_list, EViews will attempt to restructured the workfile to a regular fre-
quency. In this case you must either provide the “freq=” and “start=” options to identify
the regular frequency structure, or you must specify “none” to remove the existing structure:
pagestruct(freq=a, start=1950)
pagestruct(none)

Cross-references
For extensive discussion, see “Structuring a Workfile,” beginning on page 279 in the User’s
Guide I.

pageunlink Object Container, Data, and File Commands

Break links in all link objects and auto-updating series (formulae) in the active workfile
page.

You should use some caution with this command as you will not be prompted before the
links and auto-updating series are converted.

Syntax
pageunlink

Examples
pageunlink

breaks links in all pages of the active workfile page.

Cross-references
See Chapter 8. “Series Links,” on page 249 of the User’s Guide I for a description of link
objects, and “Auto-Updating Series” on page 219 of the User’s Guide I for a discussion of
auto-updating series.

See also Link::link (p. 530) and Link::linkto (p. 530) in the Object Reference.
562—Chapter 17.Command Reference

See unlink (p. 618) and wfunlink (p. 664) for object and workfile based unlinking,
respectively.

pageunstack Object Container, Data, and File Commands

Unstack workfile page (convert repeated observations to repeated series).

Create a new workfile page by taking series objects (series, alphas, or links) in the default
workfile page and breaking them into multiple series (or alphas), one for each distinct value
found in a user supplied list of series objects. Typically used on a page with a panel struc-
ture.

Syntax
pageunstack(options) stack_id obs_id [@ series_to_unstack]

where stack_id is a single series containing the unstacking ID values used to identify the
individual unstacked series, obs_id is a series containing the observation IDs, and
series_to_unstack is an optional list of series objects to be copied to the new workfile.

Options
namepat Specifies the pattern from which unstacked series names
=name_pattern are constructed, where “*” indicates the original series
name and “?” indicates the stack ID.
By default the name_pattern is “*?”, indicating, for exam-
ple, that if we have the IDs “US”, “UK”, “JPN”, the
unstacked series corresponding to the series GDP should be
named “GDPUS”, “GDPUK”, “GDPJPN” in the unstacked
workfile page.
wf=wf_name Optional name for the new workfile. If not provided,
EViews will create a new page in the default workfile.
page=page_name Optional name for the newly created page. If not provided,
EViews will use the next available name of the form “Unti-
tled##”, where ## is a number.

Examples
Consider a workfile that contains the series GDP and CONS which contain the values of
Gross Domestic Product and consumption for three countries stacked on top of each other.
Suppose further there is an alpha object called COUNTRY containing the observations “US”,
“UK”, and “JPN”, which identify which from which country each observation of GDP and
CONS comes. Finally, suppose there is a date series DATEID which identifies the date for
each observation. The command:
pageunstack country dateid @ gdp cons
pageunstack—563

creates a new workfile page using the workfile frequency and dates found in DATEID. The
page will contain the 6 series GDPUS, GDPUK, GDPJPN, CONSUS, CONSUK, and CONSJPN
corresponding to the unstacked GDP and CONS.

Typically the source workfile described above would be structured as a dated panel with the
cross-section ID series COUNTRY and the date ID series DATEID. Since the panel has built-in
date information, we may use the “@DATE” keyword as the DATEID. The command:
pageunstack country @date @ gdp cons

uses the date portion of the current workfile structure to identify the dates for the unstacked
page.

The stack_id must be an ordinary, or an alpha series that uniquely identifies the groupings
to use in unstacking the series. obs_id may be one or more ordinary series or alpha series,
the combination of which uniquely identify each observation in the new workfile.

You may provide an explicit list of series to unstack following an “@” immediately after the
obs_id. Wildcards may be used in this list. For example:
pageunstack country dateid @ g* c*

unstacks all series and alphas that have names that begin with “G” or “C’.

If no series_to_unstack list is provided, all series in the source workfile will be unstacked.
Thus, the two commands:
pageunstack country dateid @ *
pageunstack country dateid

are equivalent.

By default, series are named in the destination workfile page by appending the stack_id val-
ues to the original series name. Letting “*” stand for the original series name and “?” for the
stack_id, names are constructed as “*?”. This default may be changed using the “name-
pat=” option. For example:
pageunstack(namepat="?_*") country dateid @ gdp cons

creates the series US_GDP, UK_GDP, JPN_GDP, etc.

Cross-references
For additional discussion and examples, see “Unstacking a Workfile” on page 317 of the
User’s Guide I.

See also pagestack (p. 555).


564—Chapter 17.Command Reference

param Global Commands

Set parameter values.

Allows you to set the current values of coefficient vectors. The command may be used to
provide starting values for the parameters in nonlinear least squares, nonlinear system esti-
mation, and (optionally) ARMA estimation.

Syntax
param coef_name1 number1 [coef_name2 number2 coef_name3 number3…]

List, in pairs, the names of the coefficient vector and its element number followed by the
corresponding starting values for any of the parameters in your equation.

Examples
param c(1) .2 c(2) .1 c(3) .5

resets the first three values of the coefficient vector C.


coef(3) beta
param beta(2) .1 beta(3) .5

The first line declares a coefficient vector BETA of length 3 that is initialized with zeros. The
second line sets the second and third elements of BETA to 0.1 and 0.5, respectively.

Cross-references
See “Starting Values” on page 1065 of the User’s Guide II for a discussion of setting initial
values in nonlinear estimation.

plot Object Creation Commands

Line graph.

Provided for backward compatibility. See line (p. 1297).

preview Command Actions

Preview objects contained in a database or workfile.

Syntax
Database object preview:
preview(options) [path\]db_name [as shorthand_name]::object_name
preview—565

Workfile object preview:


preview(options) [path\]workfile name::object_name
preview(options) [path\]workfile name::pagename\object_name

Options
all Display all data in the series.
recent Display recent data in the series.
log Display the log of the series.
pch Display the percent change of the series data.
pchy Display the year-on-year percent change of the
series data.

Examples
preview evdbtest::x

previews object X in database EVDBTEST in the default path.


preview .\temp evdbtest.edb::y

previews object X in database EVDBTEST in the temp folder.


preview(pch,recent) dbpreview::x

previews object X in database EVDBTEST and displays the percentage change of recent data.
preview(pchy) dbpreview::x

previews object X in database EVDBTEST and displays the percentage change.


preview x

previews object X in the active workfile.


preview .\temp\testwf::x

previews object X in workfile TESTWF in the temp folder and displays the log of all the data.
preview(log,all) .\temp\testwf::x

previews object X
preview page1\x

previews object X of page1 in the active workfile.


preview .\temp\testwf::page1\x

previews object X of page1 in workfile TESTWF in the temp folder.


preview(pch,recent) .\temp\testwf::x
566—Chapter 17.Command Reference

previews object X in workfile TESTWF in the temp folder and displays the percentage
change of recent data.

print Command Actions

Sends views of objects to the default printer.

Syntax
print(options) object1 [object2 object3 …]
print(options) object_name.view_command

print should be followed by a list of object names or a view of an object to be printed. The
list of names must be of the same object type. If you do not specify the view of an object,
print will print the default view for the object.

Options
p Print in portrait orientation.
l Print in landscape orientation.

The default orientation is set by clicking on Print Setup.

Examples
print gdp log(gdp) d(gdp) @pch(gdp)

sends a table of GDP, log of GDP, first difference of GDP, and the percentage change of GDP
to the printer.
print graph1 graph2 graph3

prints three graphs on a single page.

To merge the three graphs, realign them in one row, and print in landscape orientation, you
may use the commands:
graph mygra.merge graph1 graph2 graph3
mygra.align(3,1,1)
print(l) mygra

To estimate the equation EQ1 and send the output view to the printer.
print eq1.ls gdp c gdp(-1)

Cross-references
See “Print Setup,” beginning on page 2562 of the User’s Guide II for a discussion of print
options and the Print Setup dialog.
qreg—567

See output (p. 533) for print redirection.

probit Interactive Use Commands

Estimation of binary dependent variable models with normal errors.

Equivalent to “binary(d=n)”.

See binary (p. 382).

program Programming Commands

Declare a program.

Syntax
program [path\]prog_name

Enter a name for the program after the program keyword. If you do not provide a name,
EViews will open an untitled program window. Programs are text files, not objects.

Examples
program runreg

opens a program window named RUNREG which is ready for program editing.

Cross-references
See Chapter 6. “EViews Programming,” on page 129 of the User’s Guide I for further details,
and examples of writing EViews programs.

See also open (p. 524).

qreg Interactive Use Commands

Estimate a quantile regression specification.

Syntax
qreg(options) y x1 [x2 x3 ...]
qreg(options) linear_specification
568—Chapter 17.Command Reference

Options
quant=number Quantile to be fit (where number is a value between 0 and
(default = 0.5) 1).
w=arg Weight series or expression.
Note: we recommend that, absent a good reason, you
employ the default settings Inverse std. dev. weights
(“wtype=istdev”) with EViews default scaling
(“wscale=eviews”) for backward compatibility with ver-
sions prior to EViews 7.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
cov=arg Method for computing coefficient covariance matrix: “iid”
(default=“sand- (ordinary estimates), “sandwich” (Huber sandwich esti-
wich”) mates), “boot” (bootstrap estimates).
When “cov=iid” or “cov=sandwich”, EViews will use the
sparsity nuisance parameter calculation specified in
“spmethod=” when estimating the coefficient covariance
matrix.
bwmethod=arg Method for automatically selecting bandwidth value for
(default = “hs”) use in estimation of sparsity and coefficient covariance
matrix: “hs” (Hall-Sheather), “bf” (Bofinger), “c” (Cham-
berlain).
bw =number Use user-specified bandwidth value in place of automatic
method specified in “bwmethod=”.
bwsize=number Size parameter for use in computation of bandwidth (used
(default = 0.05) when “bw=hs” and “bw=bf”).
spmethod=arg Sparsity estimation method: “resid” (Siddiqui using residu-
(default=“kernel”) als), “fitted” (Siddiqui using fitted quantiles at mean values
of regressors), “kernel” (Kernel density using residuals)
Note: “spmethod=resid” is not available when
“cov=sandwich”.
btmethod=arg Bootstrap method: “resid” (residual bootstrap), “pair” (xy-
(default= “pair”) pair bootstrap), “mcmb” (MCMB bootstrap), “mcmba”
(MCMB-A bootstrap).
qreg—569

btreps=integer Number of bootstrap repetitions


(default=100)
btseed=positive Seed the bootstrap random number generator.
integer If not specified, EViews will seed the bootstrap random
number generator with a single integer draw from the
default global random number generator.
btrnd=arg Type of random number generator for the bootstrap:
(default=“kn” or improved Knuth generator (“kn”), improved Mersenne
method previously Twister (“mt”), Knuth’s (1997) lagged Fibonacci generator
set using rndseed used in EViews 4 (“kn4”) L’Ecuyer’s (1999) combined mul-
(p. 577)). tiple recursive generator (“le”), Matsumoto and
Nishimura’s (1998) Mersenne Twister used in EViews 4
(“mt4”).
btobs=integer Number of observations for bootstrap subsampling (when
“bsmethod=pair”).
Should be significantly greater than the number of regres-
sors and less than or equal to the number of observations
used in estimation. EViews will automatically restrict val-
ues to the range from the number of regressors and the
number of estimation observations.
If omitted, the bootstrap will use the number of observa-
tions used in estimation.
btout=name (optional) Matrix to hold results of bootstrap simulations.
k=arg Kernel function for sparsity and coefficient covariance
(default=“e”) matrix estimation (when “spmethod=kernel”): “e” (Epan-
echnikov), “r” (Triangular), “u” (Uniform), “n” (Normal–
Gaussian), “b” (Biweight–Quartic), “t” (Triweight), “c”
(Cosinus).
m=integer Maximum number of iterations.
s Use the current coefficient values in “C” as starting values
(see also param (p. 564)).
s=number (default Determine starting values for equations. Specify a number
=0) between 0 and 1 representing the fraction of preliminary
least squares coefficient estimates.
Note that out of range values are set to the default.
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
570—Chapter 17.Command Reference

coef=arg Specify the name of the coefficient vector (if specified by


list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Examples
qreg y c x

estimates the default least absolute deviations (median) regression for the dependent vari-
able Y on a constant and X. The estimates use the Huber Sandwich method for computing
the covariance matrix, with individual sparsity estimates obtained using kernel methods.
The bandwidth uses the Hall and Sheather formula.
qreg(quant=0.6, cov=boot, btmethod=mcmba) y c x

estimates the quantile regression for the 0.6 quantile using MCMB-A bootstrapping to obtain
estimates of the coefficient covariance matrix.

Cross-references
See Chapter 40. “Quantile Regression,” on page 1713 of User’s Guide II for a discussion of
the quantile regression.

range Object Container, Data, and File Commands

Reset the workfile range for a regular frequency workfile.

No longer supported. See the replacement command pagestruct (p. 558).

read Object Container, Data, and File Commands

Import data from a foreign disk file into series.

May be used to import data into an existing workfile from a text, Excel, or Lotus file on disk.

Unless you need to merge data into an existing workfile page, we recommend that you use
the more powerful, easy-to-use tools for reading data (see “Creating a Workfile by Reading
from a Foreign Data Source” on page 35 of User’s Guide I).

See pageload (p. 546), and wfopen (p. 640) for command details.
read—571

Syntax
read(options) [path\]file_name name1 [name2 name3 ...]
read(options) [path\]file_name n

You must supply the name of the source file. If you do not include the optional path specifi-
cation, EViews will look for the file in the default directory. Path specifications may point to
local or network drives. If the path specification contains a space, you may enclose the
entire expression in double quotation marks.

The input specification follows the source file name. There are two ways to specify the input
series. First, you may list the names of the series in the order they appear in the file. Second,
if the data file contains a header line for the series names, you may specify the number, n, of
series in the file instead of a list of names. EViews will name the n series using the names
given in the header line. If you specify a number and the data file does not contain a header
line, EViews will name the series as SER01, SER02, SER03, and so on.

To import data into alpha series, you must specify the names of your series, and should
enter the tag “$” following the series name (e.g., “NAME $ INCOME CONSUMP”).

Options
prompt Force the dialog to appear from within a program.

File type options


t=dat, txt ASCII (plain text) files.
t=wk1, wk3 Lotus spreadsheet files.
t=xls Excel spreadsheet files.

If you do not specify the “t” option, EViews uses the file name extension to determine the
file type. If you specify the “t” option, the file name extension will not be used to determine
the file type.
Options for ASCII text files
t Read data organized by series. Default is to read by obser-
vation with series in columns.
na=text Specify text for NAs. Default is “NA”.
d=t Treat tab as delimiter (note: you may specify multiple
delimiter options). The default is “d=c” only.
d=c Treat comma as delimiter.
d=s Treat space as delimiter.
d=a Treat alpha numeric characters as delimiter.
572—Chapter 17.Command Reference

custom = Specify symbol/character to treat as delimiter.


symbol
mult Treat multiple delimiters as one.
name Series names provided in file.
label=integer Number of lines between the header line and the data.
Must be used with the “name” option.
rect (default) / [Treat / Do not treat] file layout as rectangular.
norect
skipcol = Number of columns to skip. Must be used with the “rect”
integer option.
skiprow = Number of rows to skip. Must be used with the “rect”
integer option.
comment= Specify character/symbol to treat as comment sign. Every-
symbol thing to the right of the comment sign is ignored. Must be
used with the “rect” option.
singlequote Strings are in single quotes, not double quotes.
dropstrings Do not treat strings as NA; simply drop them.
negparen Treat numbers in parentheses as negative numbers.
allowcomma Allow commas in numbers (note that using commas as a
delimiter takes precedence over this option).
currency= Specify symbol/character for currency data.
symbol

Options for spreadsheet (Lotus, Excel) files


t Read data organized by series. Default is to read by obser-
vation with series in columns.
letter_number Coordinate of the upper-left cell containing data.
(default=“b2”)
s=sheet_name Sheet name for Excel 5–8 Workbooks.

Examples
read(t=dat,na=.) a:\mydat.raw id lwage hrs

reads data from an ASCII file MYDAT.RAW in the A: drive. The data in the file are listed by
observation, the missing value NA is coded as a “.” (dot or period), and there are three
series, which are to be named ID, LWAGE, HRS (from left to right).
read(a2,s=sheet3) cps88.xls 10
rename—573

reads data from an Excel file CPS88 in the default directory. The data are organized by obser-
vation, the upper left data cell is A2, and 10 series are read from a sheet named SHEET3
using names provided in the file.
read(a2, s=sheet2) "\\network\dr 1\cps91.xls" 10

reads the Excel file CPS91 from the network drive specified in the path.

Cross-references
See “Importing Data” on page 152 of User’s Guide I for a discussion and examples of import-
ing data from external files.

See also write (p. 666).

rename Object Utility Commands

Rename an object in the active workfile or database.

Syntax
rename old_name new_name [old_name1 new_name1 [old_name2 new_name2 [...]]]

After the rename keyword, list the pairs of old object names followed by the new names.
Note that the name specifications may include matching wildcard patterns.

Examples
rename temp_u u2

renames an object named TEMP_U as U2.


rename aa::temp_u aa::u2

renames the object TEMP_U to U2 in database AA.


rename a* b*

renames all objects beginning with the letter “A” to begin with the letter “B”.
rename a1 a2 b1 b2

renames A1 to A2 and B1 to B2.

Cross-references
See Chapter 4. “Object Basics,” on page 107 of User’s Guide I for a discussion of working
with objects in EViews.
574—Chapter 17.Command Reference

reset Interactive Use Commands

Compute Ramsey’s regression specification error test.

Syntax
reset(n, options)

You must provide the number of powers of fitted terms n to include in the test regression.

Options
prompt Force the dialog to appear from within a program.
p Print the test result.

Examples
ls lwage c edu race gender
reset(2)

carries out the RESET test by including the square and the cube of the fitted values in the
test equation.

Cross-references
See “Ramsey's RESET Test” on page 1258 of User’s Guide II for a discussion of the RESET
test.

rmvnorm Object Assignment Commands

Generate multivariate random normal values.

Fill group of series with multivariate normals random draws.

Syntax
rmvnorm(x, S[, prefix]))
rmvnormc(x, S[, prefix]))
rmvnormi(x, S[, prefix]))
mvnormci(x, S[, prefix]))

where x is an object as described below matrix, and sym S describes the covariance matrix
as described below.
• If x doesn't exist, a group object is first created and populated with series named
“<prefix>1”, “<prefix>2”, and so on. If omitted, the default prefix is "SER".
rnd—575

• If x is a group, the command fills each observation of the contained series with a draw
from the distribution.
• If x is a vector, the command fills the vector with a single draw from the distribution.
• If x is a matrix, the command fills each row of the matrix with a draw from the distri-
bution.

There are four distinct commands in this family which correspond to different interpreta-
tions for S. These forms are distinguished by the characters in the command name that fol-
low the initial string “rmvnorm”:

“” Supply S , the covariance matrix of distribution.


“c” Supply the Cholesky decomposition of S . This form is more
efficient when performing multiple draws from the same distri-
bution (compute the Cholesky once, but sample many times).
–1
“i “ Supply S . This form is more efficient than explicitly inverting
–1
S to supply S .
–1
“ic” Supply the Cholesky decomposition of S . This form combines
the efficiencies of the above forms.

Examples
sym a = @inner(@mnrnd(100, 10))
matrix(1000, 10) x
rmvnorm(x, a)
rmvnormc(x, @cholesky(a))
rmvnormi(x, @inverse(a))
rmvnormic(x, @cholesky(@inverse(a))

Cross-references
For random generator functions, see “Statistical Distributions,” on page 686 and in particu-
lar, @mrnd (p. 1000), @mnrnd (p. 982), and @rmvnorm (p. 1085).

For related commands, see nrnd (p. 523), rnd (p. 575), rndint (p. 576), and rmvnorm
(p. 574). See also rndseed (p. 577).

rnd Object Assignment Commands

Generate uniform random draws.

The rnd command fills series, vector, and matrix objects with (pseudo) random values
drawn uniformly from zero to ones. When used with a series, rnd command ignores the
current sample and fills the entire object.
576—Chapter 17.Command Reference

Syntax
rnd(object_name)

Fill object_name with uniform random numbers.

Examples
matrix(30, 4) m1
rnd(m1)

Cross-references
For random generator functions, see “Statistical Distributions,” on page 686 and in particu-
lar, @mrnd (p. 1000), @mnrnd (p. 982), and @rmvnorm (p. 1085).

For related commands, see nrnd (p. 523), rndint (p. 576), and rmvnorm (p. 574). See also
rndseed (p. 577).

rndint Object Assignment Commands

Generate uniform random integers.

The rndint command fills series, vector, and matrix objects with (pseudo) random integers
drawn uniformly from zero to a user specified maximum. The rndint command ignores the
current sample and fills the entire object with random integers.

Syntax
rndint(object_name, n)

Type the name of the series, vector, or matrix object to fill, followed by an integer value rep-
resenting the maximum value n of the random integers. n should a positive integer.

Examples
series index
rndint(index,10)

fills the entire series INDEX with integers drawn randomly from 0 to 10. Note that unlike
standard series assignment using genr, rndint ignores the current sample and fills the
series for the entire workfile range.
sym(3) var3
rndint(var3,5)

fills the entire symmetric matrix VAR3 with random integers ranging from 0 to 5.
rndseed—577

Cross-references
For random generator functions, see “Statistical Distributions,” on page 686 and in particu-
lar, @mrnd (p. 1000), @mnrnd (p. 982), and rmvnorm (p. 574).

For related commands, see nrnd (p. 523), rnd (p. 575), and rmvnorm (p. 574). See also
rndseed (p. 577).

rndseed Global Commands

Seed the random number generator.

Use rndseed when you wish to generate a repeatable sequence of random numbers, or to
select the generator to be used.

Note that EViews 5 has updated the seeding routines of two of our pseudo-random number
generators (backward compatible options are provided). It is strongly recommended that
you use new generators.

Syntax
rndseed(options) integer

Follow the rndseed keyword with the optional generator type and an integer for the seed.

Options
type=arg Type of random number generator: improved Knuth gener-
(default=“kn”) ator (“kn”), improved Mersenne Twister (“mt”), Knuth’s
(1997) lagged Fibonacci generator used in EViews 4
(“kn4)”, L’Ecuyer’s (1999) combined multiple recursive
generator (“le”), Matsumoto and Nishimura’s (1998)
Mersenne Twister used in EViews 4 (“mt4”).

When EViews starts up, the default generator type is set to the improved Knuth lagged Fibo-
nacci generator. Unless changed using rndseed, Knuth’s generator will be used for subse-
quent pseudo-random number generation.

Knuth L’Ecuyer Mersenne Twister


(“kn4”) (“le”) (“mt4”)
Period 129 319 19937
2 2 2 –1
7 27.3 secs 15.7 secs 1.76 secs
Time (for 10 draws)
Cases failed Diehard test 0 0 0
578—Chapter 17.Command Reference

Examples
rndseed 123456
genr t3 = @qtdist(rnd,3)
rndseed 123456
genr t30 = @qtdist(rnd,30)

generates random draws from a t-distribution with 3 and 30 degrees of freedom using the
same seed.

Cross-references
See the list of available random number generators in “Statistical Distributions” on page 686
of Command and Programming Reference.

At press time, further information on the improved seeds may be found on the web at the
following addresses:

Knuth generator: http://sunburn.stanford.edu/~knuth/news02.html#rng

Mersenne twister: http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html

See also nrnd (p. 523), rnd (p. 575), rndint (p. 576), and rmvnorm (p. 574).

References
Knuth, D. E. (1997). The Art of Computer Programming, Volume 2, Semi-numerical Algorithms,
3rd edition, Reading, MA: Addison-Wesley Publishing Company. Note: the C implementa-
tion of the lagged Fibonacci generator is described in the errata to the 2nd edition,
downloadable from Knuth's web site.
L’Ecuyer, P. (1999). “Good Parameters and Implementations for Combined Multiple Recursive Ran-
dom Number Generators,” Operations Research, 47(1), 159-164
Matsumoto, M. and T. Nishimura (1998). “Mersenne Twister: A 623-Dimensionally Equidistrib-
uted Uniform Pseudo-Random Number Generator,” ACM Transactions on Modeling and
Computer Simulation, 8(1), 3-30.

robustls Equation Methods

Estimates an equation using robust least squares.

You may perform three different types of robust estimation: M-estimation, S-estimation
and MM-estimation.

Syntax:
robustls(options) y x1 [x2 x3…]

Enter the robustls keyword, followed by the dependent variable and a list of the regres-
sors.
robustls—579

Options
method=arg Robust estimation method: “m” (M-estimation), “s”
(default=“m”) (S-estimation) or “mm” (MM-estimation).
cov=arg Covariance method type: “type1”, “type2”, or “type3”.
(default=“type1”)
tuning=number Specify a value for the tuning parameter. If a value is
not specified, EViews will use the default tuning
parameter for the type of estimation and weighting
function (if applicable).
c=s Convergence criterion. The criterion will be set to the
nearest value between 1e-24 and 0.2.
coef=arg Specify the name of the coefficient vector (if specified
by list); the default behavior is to use the “C” coeffi-
cient vector.
m=integer Maximum number the number of iterations.
prompt Force the dialog to appear from within a program.
p Print results.

M-estimation Options
fn=arg Weighting function used during M-estimation:
(default=“bisquare”) “andrews” (Andrews), “bisquare” (Bisquare), “cau-
chy” (Cauchy), “fair”, “huber”, “huberbi” (Huber-
bisquare), “logistic” (Logistic), “median”, “tal” (Tal-
worth), “Welsch” (Welsch).
scale=arg Scaling method used for calculating the scalar parame-
(default=“madzero”) ter during M estimation: “madzero” (median absolute
deviation, zero centered), “madmed” (median abso-
lute deviation, median centered), "huber" (Huber scal-
ing).
hmat Use the hat-matrix to down-weight observations with
high leverage.
580—Chapter 17.Command Reference

S and MM estimation options


compare = integer Number of comparison sets.
(default=4)
refine = integer Number of refinements.
(default= 2)
trials = integer Number of trials.
(default=200)
subsmpl=integer Specifies the size of the subsamples. Note, the default
is number of coefficients in the regression.
seed=number Specifies the random number generator seed
rng=arg Specifies the type of random number generator. The
key can be; improved Knuth generator (“kn”),
improved Mersenne Twister (“mt”), Knuth’s (1997)
lagged Fibonacci generator used in EViews 4 (“kn4”)
L’Ecuyer’s (1999) combined multiple, recursive gener-
ator (“le”), Matsumoto and Nishimura’s (1998)
Mersenne Twister used in EViews 4 (“mt4”).

MM estimation options
mtuning=arg M-estimator tuning parameter.
Note the S-estimator tuning parameter is set with the
“tuning=” option outlined above.
hmat Use the hat-matrix to down-weight observations with
high leverage during m-estimation.

Examples
The following examples use the “Rousseeuw and Leroy.wf1” file located in the EViews
application data directory.
robustls salinity c lagsal trend discharge

This line estimates a simple M-type robust estimation, with SALINITY as the dependent
variable, and a constant, LAGSAL, TREND and DISCHARGE as independent variables.

The line:
robustls(method=mm, tuning=2.937, mtuning=3.44, cov=type2)
salinity c lagsal trend discharge

estimates the same model, but using MM-estimation, with an S tuning constant of 2.937, an
M tuning constant of 3.44, and using Huber Type II standard errors.
run—581

Cross-references
See Chapter 33. “Robust Least Squares,” beginning on page 1521 of User’s Guide II for dis-
cussion.

rowplace Matrix Utility Commands

Place vector in row of a matrix.

Place a column or rowvector object in a specified row of a matrix.

Syntax
rowplace(m, r, n)

Places the column vector or rowvector r into the matrix m at row n. The number of columns
in m and r must match, and row n must exist within m.

Examples
matrix m1 = @mnrnd(30, 5)
matrix r1 = @mnrnd(1, 5)
rowplace(m1, r1, 4)

places R1 in the fourth row of M1.

Cross-references
See also colplace (p. 410) and matplace (p. 518).

run Programming Commands

Run a program.

The run command executes a program. The program may be located in memory or stored in
a program file on disk.

Syntax
run(options) [path\]prog_name(prog_options) [%0 %1 …]

If you wish to pass one or more options to the program, you should enclose them in paren-
theses immediately after the filename. If the program has arguments, you should list them
after the filename.

EViews first checks to see if the specified program is in memory. If the program is not
located, EViews then looks for the program on disk in the current working directory, or in the
582—Chapter 17.Command Reference

specified path. The program file should have a “.PRG” extension, which you need not spec-
ify in the prog_name.

Options
integer Set maximum errors allowed before halting the program.
(default=1)
c Run program file without opening a window for display of
the program file.
verbose / quiet Verbose mode in which messages will be sent to the status
line at the bottom of the EViews window (slower execu-
tion), or quiet mode which suppresses workfile display
updates (faster execution).
v/q Same as [verbose / quiet].
ver4 / ver5 Execute program in [version 4 / version 5] compatibility
mode.
this=object_na Set the _this object for the executed program. If omitted,
me the executed program will inherit the _this object from
the parent program, or from the current active workfile
object when the exec command is issued from the com-
mand window.

Examples
run(q) simul(h=2) x xhat

quietly runs a program named “Simul.prg” from the default directory using options string
“h=2” and arguments %0=X and %1=XHAT.

Since run is a command, it may also be placed in a program file. You should note that if you
put the run command in a program file and then execute the program, EViews will stop
after executing the program referred to by the run command. For example, if you have a pro-
gram containing:
run simul
print x

the print statement will not be executed since execution will stop after executing the com-
mands in “Simul.prg”. If this behavior is not intended, you should consider using the exec
(p. 444) command or an include (p. 349) statement.

Cross-references
See “Executing a Program” on page 133 of the User’s Guide I for further details.

See also exec (p. 444) and include (p. 349).


saveprgini—583

save Object Container, Data, and File Commands

Save current workfile to disk.

This usage is provided only for backward compatibility, as it has been replaced with the
equivalent wfsave (p. 656) command.

Syntax
save [path\]file_name

Follow the keyword with a name for the file. If an explicit path is not specified, the file will
be stored in the default directory, as set in the File Locations global options.

Examples
save MyWorkfile

saves the current workfile with the name MYWORKFILE.WF1 in the default directory.
save c:\data\MyWF1

saves the current workfile with the name MYWF1.WF1 in the specified directory.

Cross-references
See wfsave (p. 656).

saveprgini Programming Commands

Saves program variables to an “.ini” file.

Syntax
saveprogini([file=filename]) [section]name value

Saves the value (either string or scalar) into the name under the section [section] in the “.ini”
file specified by filename. If no section is provided, a [default] section is used. If no filename
is given, EViews will create an “.ini” file with the same name as the current running pro-
gram in the same directory. If the program is untitled, the current default directory is used.
This command must be run from inside a program.

Example
saveprgini(file="c:\temp\myini.ini") hello 3

This will create a “.ini” file containing:


[default]
hello=3
584—Chapter 17.Command Reference

You may then load the value into a string using @loadprgini (p. 945):
create u 10
string a = @loadprgini("hello", "c:\temp\myini.ini")

Cross-references
See also @loadprgini (p. 945).

seas Interactive Use Commands

Seasonal adjustment.

The seas command carries out seasonal adjustment using either the ratio to moving aver-
age, or the difference from moving average technique.

EViews also performs Census X11 and X12 seasonal adjustment. For details, see
Series::x11 (p. 885) and Series::x12 (p. 885) in the Object Reference.

Syntax
seas(options) series_name name_adjust [name_fac]

List the name of the original series and the name to be given to the seasonally adjusted
series. You may optionally include an additional name for the seasonal factors. seas will
display the seasonal factors using the convention of the Census X11 program.

Options
m Multiplicative (ratio to moving average) method.
a Additive (difference from moving average) method.
prompt Force the dialog to appear from within a program.

Examples
seas(a) pass pass_adj pass_fac

seasonally adjusts the series PASS using the additive method, and saves the adjusted series
as PASS_ADJ and the seasonal factors as PASS_FAC.

Cross-references
See “Seasonal Adjustment” on page 507 of the User’s Guide I for a discussion of seasonal
adjustment methods.

See also seasplot (p. 1321), Series::x11 (p. 885), and Series::x12 (p. 885) in the
Object Reference.
setcell—585

setcell Table Commands

Insert contents into cell of a table.

The setcell command puts a string or number into a cell of a table.

Syntax
setcell(table_name, r, c, content[, "options"])

Options
Provide the following information in parentheses in the following order: the name of the
table object, the row number, r, of the cell, the column number, c, of the cell, a number or
string to put in the cell, and optionally, a justification and/or numerical format code. A
string of text must be enclosed in double quotes.

The justification options are:


c Center the text/number in the cell.
r Right-justify the text/number in cell.
l Left-justify the text/number in cell.

The numerical format code determines the format with which a number in a cell is dis-
played; cells containing strings will be unaffected. The format code can either be a positive
integer, in which case it specifies the number of decimal places to be displayed after the dec-
imal point, or a negative integer, in which case it specifies the total number of characters to
be used to display the number. These two cases correspond to the Fixed decimal and Fixed
character fields in the number format dialog.

Note that when using a negative format code, one character is always reserved at the start of
a number to indicate its sign, and that if the number contains a decimal point, that will also
be counted as a character. The remaining characters will be used to display digits. If the
number is too large or too small to display in the available space, EViews will attempt to use
scientific notation. If there is insufficient space for scientific notation (six characters or less),
the cell will contain asterisks to indicate an error.

Examples
setcell(tab1, 2, 1, "Subtotal")

puts the string “Subtotal” in row 2, column 1 of the table object named TAB1.
setcell(tab1, 1, 1, "Price and cost", "r")
586—Chapter 17.Command Reference

puts the a right-justify string “Price and cost” in row 1, column 1 of the table object named
TAB1.

Note that in general, that unless you wish to control the formatting, assignment statements
of the form
Mytable(1,1) = "hello"

are easier than using the default setcell statement:


Setcell(mytable,1,1,"hello")

Cross-references
Chapter 3. “Working with Tables and Spreadsheets,” on page 57 describes table formatting
using commands. See “Table Objects,” beginning on page 937 of the User’s Guide I for a dis-
cussion and examples of table formatting in EViews.

See also Table::setjust (p. 1102) and Table::setformat (p. 1096) in the Object Refer-
ence. Note that this command is supported primarily for backward compatibility. There is a
more extensive set of table procs for working with and customizing tables. See “Table
Procs,” on page 1072 in Object Reference.

setcolwidth Table Commands

Set width of a column of a table.

Provided for backward compatibility. See Table::setwidth (p. 1108) in the Object Refer-
ence for the new method of setting the width of table and spreadsheet columns.

Syntax
setcolwidth(table_name, c, width)

Options
To change the width of a column, provide the following information in parentheses, in the
following order: the name of the table, the column number c, and the number of characters
width for the new width. EViews measures units in terms of the width of a numeric charac-
ter. Because different characters have different widths, the actual number of characters that
will fit may differ slightly from the number you specify. By default, each column is approxi-
mately 10 characters wide.

Examples
setcolwidth(mytab,2,20)

sets the second column of table MYTAB to fit approximately 20 characters.


seterrcount—587

Cross-references
Chapter 3. “Working with Tables and Spreadsheets,” on page 57 of User’s Guide I describes
table formatting using commands. See also “Table Objects” on page 937 of User’s Guide I for
a discussion and examples of table formatting in EViews.

Note that this command is supported primarily for backward compatibility. There is a more
extensive set of table procs for working with and customizing tables. See “Table Procs,” on
page 1072 in the Object Reference.

See also Table::setwidth (p. 1108) and Table::setheight (p. 1100) in the Object Refer-
ence.

seterr Programming Commands

Set a user-specified execution error.

Syntax
seterr string

sets an execution error using the specified string. May only be used in programs.

Cross-references
See also @errorcount (p. 877), @maxerrcount (p. 966), clearerrs (p. 393), and set-
maxerrs (p. 588).

seterrcount Programming Commands

Set the current program execution error count.

Syntax
seterrcount integer

sets the current error count to the specified integer value. May only be used in programs.

Cross-references
See also @errorcount (p. 877), @maxerrcount (p. 966), clearerrs (p. 393), seterr
(p. 587), and setmaxerrs (p. 588).
588—Chapter 17.Command Reference

setmaxerrs Programming Commands

Set the maximum number of errors that a program may encounter before execution is
halted.

Syntax
setmaxerrs integer

sets the maximum number of errors to the specified integer value.

Cross-references
See also @errorcount (p. 877), @maxerrcount (p. 966), clearerrs (p. 393), and seter-
rcount (p. 587).

setline Table Commands

Place a double horizontal line in a table.

Provided for backward compatibility. For a more general method of setting the line charac-
teristics and borders for a set of table cells, see the table proc Table::setlines (p. 1103)
See also Table::setwidth (p. 1108) and Table::setheight (p. 1100) in the Object Refer-
ence.

Syntax
setline(table_name, r)

Options
Specify the name of the table and the row number r in which to place the horizontal line.

Examples
setline(tab3,8)

places a (double) horizontal line in the eighth row of the table object TAB3.

Cross-references
Chapter 3. “Working with Tables and Spreadsheets,” on page 57 of User’s Guide I describes
table formatting using commands. See also “Table Objects” on page 937 of User’s Guide I for
a discussion and examples of table formatting in EViews.

See Table::setlines (p. 1103) in the Object Reference for more flexible line drawing tools.
Note that this command is supported primarily for backward compatibility. There is a more
show—589

extensive set of table procs for working with and customizing tables. See “Table Procs,” on
page 1072 in the Object Reference.

shell Programming Commands

Start the Windows command shell, optionally executing a command.

Syntax
shell(options) [arg1 arg2 arg3…]

See spawn (p. 596) for available options. By default, the Windows command shell will be
started in hidden mode with the exit code for success set to zero.

Examples
shell mkdir c:\newdir

makes a new directory “c:\newdir”.


shell(out=flist) dir /b *.wf1

lists all workfiles in the current directory, saving output in a table named FLIST.

Cross-references
See spawn (p. 596) for details on spawning a new process.

show Command Actions

Display objects.

The show command displays series or other objects on your screen. A scalar object is dis-
played in the status line at the bottom of the EViews window.

Syntax
show object_name.view_command
show object1 [object2 object3 ...]

The command show should be followed by the name of an object, or an object name with
an attached view.

For series and graph objects, show can operate on a list of names. The list of names must be
of the same type. show creates and displays an untitled group or multiple graph object.

Examples
genr x=nrnd
show x.hist
590—Chapter 17.Command Reference

close x

generates a series X of random draws from a standard normal distribution, displays the his-
togram view of X, and closes the series window.
show wage log(wage)

opens an untitled group window with the spreadsheet view of the two series.
freeze(gra1) wage.hist
genr lwage=log(wage)
freeze(gra2) lwage.hist
show gra1 gra2

opens an untitled graph object with two histograms.

Cross-references
See “Object Commands” on page 21 for discussion.

Chapter 1. “Object View and Procedure Reference,” on page 3 in the Object Reference pro-
vides a complete listing of the views of the various objects.

See also close (p. 393) and do (p. 435).

smooth Interactive Use Commands

Forecasts a series using one of a number of exponential smoothing techniques. By default,


smooth estimates the damping parameters of the smoothing model to minimize the sum of
squared forecast errors, but you may specify your own values for the damping parameters.

smooth automatically calculates in-sample forecast errors and puts them into the series
RESID.

Syntax
smooth(method) series_name smooth_name [freq]

You should follow the smooth keyword with the name of the series to smooth and a name
for the smoothed series. You must also specify the smoothing method in parentheses. The
optional freq may be used to override the default for the number of periods in the seasonal
cycle. By default, this value is set to the workfile frequency (e.g. — 4 for quarterly data). For
undated data, the default is 5.
smooth—591

Options
Smoothing method options
s[,x] Single exponential smoothing for series with no trend. You
may optionally specify a number x between zero and one
for the mean parameter.
d[,x] Double exponential smoothing for series with a trend. You
may optionally specify a number x between zero and one
for the mean parameter.
n[,x,y] (default) Holt-Winters without seasonal component. You may
optionally specify numbers x and y between zero and one
for the mean and trend parameters, respectively.
a[,x,y,z] Holt-Winters with additive seasonal component. You may
optionally specify numbers x, y, and z, between zero and
one for the mean, trend, and seasonal parameters, respec-
tively.
m[,x,y,z] Holt-Winters with multiplicative seasonal component. You
may optionally specify numbers x, y, and z, between zero
and one for the mean, trend, and seasonal parameters,
respectively.

Other Options:
forcsmpl = arg Forecast sample (optional). If forecast sample is not pro-
vided, the workfile sample will be employed.
prompt Force the dialog to appear from within a program.
p Print a table of forecast statistics.

If you wish to set only some of the damping parameters and let EViews estimate the other
parameters, enter the letter “e” where you wish the parameter to be estimated.

If the number of seasons is different from the frequency of the workfile (an unusual case
that arises primarily if you are using an undated workfile for data that are not monthly or
quarterly), you should enter the number of seasons after the smoothed series name. This
optional input will have no effect on forecasts without seasonal components.

Examples
smooth(s) sales sales_f

smooths the SALES series by a single exponential smoothing method and saves the
smoothed series as SALES_F. EViews estimates the damping (smoothing) parameter and dis-
plays it with other forecast statistics in the SALES series window.
smooth(n,e,.3) tb3 tb3_hw
592—Chapter 17.Command Reference

smooths the TB3 series by a Holt-Winters no seasonal method and saves the smoothed
series as TB3_HW. The mean damping parameter is estimated while the trend damping
parameter is set to 0.3.
smpl @first @last-10
smooth(m,.1,.1,.1) order order_hw
smpl @all
graph gra1.line order order_hw
show gra1

smooths the ORDER series by a Holt-Winters multiplicative seasonal method leaving the last
10 observations. The damping parameters are all set to 0.1. The last three lines plot and dis-
play the actual and smoothed series over the full sample.

Cross-references
See “Exponential Smoothing” on page 599 of the User’s Guide I for a discussion of exponen-
tial smoothing methods.

smpl Global Commands

Set sample range.

The smpl command sets the workfile sample to use for statistical operations and series
assignment expressions.

Syntax
smpl smpl_spec
smpl sample_name

List the date or number of the first observation and the date or number of the last observa-
tion for the sample. Rules for specifying dates are given in “Dates” on page 104. The sample
spec may contain more than one pair of beginning and ending observations.

The smpl command also allows you to select observations on the basis of conditions speci-
fied in an if statement. This enables you to use logical operators to specify what observa-
tions to include in EViews’ procedures. Put the if statement after the pairs of dates.

You can also use smpl to set the current observations to the contents of a named sample
object; put the name of the sample object after the keyword.

Special keywords for smpl


The following “@-keywords” can be used in a smpl command:
smpl—593

@all The entire workfile range.


@first The first observation in the workfile.
@last The last observation in the workfile.

The following frequency functions may also be used:


@year The four digit year in which the current observation begins.
@quarter The quarter of the year in which the current observation
begins.
@month The month of the year in which the current observation
begins.
@day The day of the month in which the current observation
begins.
@weekday The day of the week in which the current observation
begins, where Monday is given the number 1 and Sunday
is given the number 7.
@hour The observation hour as an integer. (9:30AM returns 9,
5:15PM returns 17.)
@minute The observation minute as an integer. (9:30PM returns 30.)
@second The observation second as an integer.
@hourf The observation time as a floating point hour. (9:30AM
returns 9.5, 5:15PM returns 17.25.)

In panel settings, you may use the additional keywords:


@firstmin The earliest of the first observations (computed across
cross-sections).
@firstmax The latest of the first observations.
@lastmin The earliest of the last observations.
@lastmax The latest of the last observations.

Examples
smpl 1955m1 1972m12

sets the workfile sample from 1955M1 to 1972M12.


smpl @first 1940 1946 1972 1975 @last

excludes observations (or years) 1941–1945 and 1973–1974 from the workfile sample.
smpl if union=1 and edu<=15
594—Chapter 17.Command Reference

sets the sample to those observations where UNION takes the value 1 and EDU is less than
or equal to 15.
sample half @first @first+@obs(x)/2
smpl half
smpl if x>0
smpl @all if x>0

The first line declares a sample object named HALF which includes the first half of the series
X. The second line sets the sample to HALF and the third line sets the sample to those obser-
vations in HALF where X is positive. The last line sets the sample to those observations
where X is positive over the full sample.

The sample may be set for intraday data using optional times after the dates. For example,
smpl 1/3/2000 10AM 12/30/2000 2PM

removes any observations before 10AM on 1/3/2000 and after 2PM on 12/30/2000.
smpl if @hourf<=9.5 and @hourf<=14.5

sets the sample to include only observations between and including 9:30AM and 2:30PM.
smpl if @minute=0 or @minute=30

selects only observations that appear on the half hour.


smpl if @weekday=1 and @hourf=10

sets the sample to include only observations that appear on Mondays at 10AM.

Cross-references
See “Samples” on page 142 of the User’s Guide I for a discussion of samples in EViews.

See also Sample::set (p. 744) and Sample::sample (p. 743) in the Object Reference.

solve Interactive Use Commands

Solve the model.

solve finds the solution to a simultaneous equation model for the set of observations spec-
ified in the current workfile sample.

Syntax
solve(options) model_name

Note: when solve is used in a program (batch mode) models are always solved over the
workfile sample. If the model contains a solution sample, it will be ignored in favor of the
workfile sample.
sort—595

You should follow the name of the model after the solve command. The default solution
method is dynamic simulation. You may modify the solution method as an option.

solve first looks for the specified model in the current workfile. If it is not present, solve
attempts to fetch a model file (.DBL) from the default directory or, if provided, the path
specified with the model name.

Options
solve can take any of the options available in Model::solveopt (p. 643) in the Object Ref-
erence.

Examples
solve mod1

solves the model MOD1 using the default solution method.


solve(m=500,e) nonlin2

solves the model NONLIN2 with an extended search of up to 500 iterations.

Cross-references
See Chapter 52. “Models,” on page 2183 of User’s Guide II for a discussion of models.

See also Model::model (p. 631), Model::msg (p. 632) and Model::solveopt (p. 643) in
the Object Reference.

sort Object Container, Data, and File Commands

Sort the current workfile page.

The sort command sorts all series in the workfile page on the basis of the values of one or
more of the series. For purposes of sorting, NAs are considered to be smaller than any other
value. By default, EViews will sort the series in ascending order. You may use options to
override the sort order.

EViews will first remove any workfile structures and then will sort the workfile using the
specified settings.

Syntax
sort(options) arg1 [arg2 arg3…]

List the name of the series or groups by which you wish to sort the workfile. If you list two
or more series, sort uses the values of the second series to resolve ties from the first series,
and values of the third series to resolve ties from the second, and so on.
596—Chapter 17.Command Reference

Options
d sort in descending order.

Examples
sort(d) inc

sorts all series in the workfile in order of the INC series with the highest value of INC first.
NAs in INC (if any) will be placed at the bottom.
sort gender race wage

sorts all series in the workfile in order of the values of GENDER from low to high, with ties
resolved by ordering on the basis of RACE, with further ties resolved by ordering on the
basis of WAGE.

Cross-references
See “Sorting a Workfile” on page 331 of User’s Guide I.

spawn Programming Commands

Spawn a new process.

Syntax
spawn(options) filename [arg1 arg2 arg3…]

Follow the keyword with a filename indicating the process to spawn, and optional argu-
ments to be passed to the process.

Options
“n” or “normal” Create process in normal mode. The process will typically
create a maximized window and may wait for user input.
“m” or Create process in a minimized window. Note that some
“minimized” applications may not accept requests to run in minimized
mode.
“h” or “hidden” Create process in hidden mode (without a visible window).
Note that some applications may not accept requests to run
in hidden mode.
stats—597

t=isecs Specifies the maximum time in milliseconds that EViews


should wait for the process to complete. If the timeout
interval is reached and the process has not completed,
EViews will generate an error. A timeout setting of zero
may be used to indicate that EViews should not wait for
the spawned process to complete. If no timeout option is
provided, EViews will wait indefinitely for the process to
complete.
exit=icode Specifies the exit code that the process will return if it is
completed successfully. If the process returns an exit code
other than the specified value, EViews will generate an
error. If the exit code option is not specified, EViews will
not generate an error no matter what exit code is returned
by the process.
out = If an output table name is specified, EViews will capture
tablename any data written to standard output by the spawned pro-
cess and store it into a table object with the specified name
in the workfile. Note that this option will have no effect
unless either the minimized or hidden option is used and
the timeout value is not zero.

Examples
spawn "c:\program files\microsoft office\office11\excel.exe"
test.xls

starts a new Excel process, passing it the command line argument “test.xls”.

Cross-references
See shell (p. 589) for information on starting a Windows command shell.

stats Interactive Use Commands

Descriptive statistics.

Computes and displays a table of means, medians, maximum and minimum values, stan-
dard deviations, and other descriptive statistics of one or more series or a group of series.

stats creates an untitled group containing all of the specified series, and opens a statistics
view of the group. By default, if more than one series is given, the statistics are calculated
for the common sample.

Syntax
stats(options) ser1 [ser2 ser3 …]
598—Chapter 17.Command Reference

Options
p Print the stats table.

Examples
stats height weight age

opens an untitled group window displaying the histogram and descriptive statistics for the
common sample of the three series.

Cross-references
See “Descriptive Statistics & Tests” on page 450 and page 667 of User’s Guide I for a discus-
sion of the descriptive statistics views of series and groups.

See also boxplot (p. 1278) and hist (p. 477).

statusline Programming Commands

Send text to the status line.

Displays a message in the status line at the bottom of the EViews main window. The mes-
sage may include text, control variables, and string variables.

Syntax
statusline message_string

Examples
statusline Iteration Number: !t

Displays the message “Iteration Number: !t” in the status line replacing “!t” with the current
value of the control variable in the program.

Cross-references
See Chapter 6. “EViews Programming,” on page 129 of User’s Guide I for a discussion and
examples of programs, control variables and string variables.

See also commandcap (p. 410).

stom Matrix Utility Commands

Convert series or group to a matrix object after removing NAs.

Series-TO-Matrix object: convert the data in a series or group or series into a matrix after
removing rows with missing values.
stomna—599

Syntax
stom(o1, o2, smp)

where o1 is a series, alpha, or group, o2 is a corresponding vector, svector, or matrix, and


smp is an optional sample.
• If o1 is a series, stom fills the vector o2 with data from the o1 using the optional sam-
ple object smp or the workfile sample. o2 will be resized accordingly. If any observa-
tion has the value “NA”, the observation will be omitted from the vector.
• If o1 is a group, stom fills the matrix o2 with data from o1 using the optional sample
object smp or the workfile sample. o2 will be resized accordingly. The series in o1 are
placed in the columns of o2 in the order they appear in the group spreadsheet. If any
of the series in the group has the value “NA” for a given series observation or blank
for an alpha, the observation will be omitted for all series.
• If o1 is an alpha-series, stom fills the svector o2 with data from o1 using the optional
sample object smp or the workfile sample. o2 will be resized accordingly. If any of the
observation is blank, the observation will be omitted from the result.

For a conversion method that preserves NAs, see stomna (p. 599).

Examples
stom(ser1,v1)
stom(ser1,v2,smp1)
stom(grp1,m1)
stom(grp1,m2,smp1)

Cross-references
See also mtos (p. 522), @convert (p. 764), stomna (p. 599), and ttom (p. 617).

stomna Matrix Utility Commands

Convert series or group to a matrix object, retaining NAs.

Series-TO-Matrix object with NAs: convert the data in a series or group or series into a
matrix, retaining rows with missing values.

Syntax
stom(o1, o2, smp)

where o1 is a series, alpha, or group, o2 is a corresponding vector, svector, or matrix, and


smp is an optional sample.
600—Chapter 17.Command Reference

• If o1 is a series, stomna fills the vector o2 with data from o1 using the optional sam-
ple object smp or the workfile sample. o2 will be resized accordingly. All “NA” values
in the series will be assigned to the corresponding vector elements.
• If o1 is a group, stomna fills the matrix o2 with data from o1 using the optional sam-
ple object smp or the workfile sample. o2 will be resized accordingly. The series in o1
are placed in the columns of o2 in the order they appear in the group spreadsheet. All
NAs will be assigned to the corresponding matrix elements.
• If o1 is an alpha-series, stomna fills the svector o2 with data from o1 using the
optional sample object smp or the workfile sample. o2 will be resized accordingly. All
“NA” values (blank elements of the alpha) will be assigned to the corresponding vec-
tor elements.

For conversion methods that automatically remove observations with NAs, see @convert
(p. 764) and stom (p. 598).

Examples
stom(ser1,v1)
stom(ser1,v2,smp1)
stomna(grp1,m1)
stomna(grp1,m2,smp1)

Cross-references
See also mtos (p. 522), @convert (p. 764), stom (p. 598), and ttom (p. 617).

store Object Container, Data, and File Commands

Store objects in databases and databank files.

Stores one or more objects in the current workfile in EViews databases or individual data-
bank files on disk. The objects are stored under the name that appears in the workfile.

Syntax
store(options) object_list

Follow the store command keyword with a list of object names (each separated by a space)
that you wish to store. The default is to store the objects in the default database. (This
behavior is a change from EViews 2 and earlier where the default was to store objects in indi-
vidual databank files).

You may precede the object name with a database name and the double colon “::” to indi-
cate a specific database. You can also specify the database name as an option in parenthe-
store—601

ses, in which case all objects without an explicit database name will be stored in the
specified database.

You may use wild card characters “?” (to match any single character) or “*” (to match zero
or more characters) in the object name list. All objects with names matching the pattern will
be stored.

You can optionally choose to store the listed objects in individual databank files. To store in
files other than the default path, you should include a path designation before the object
name.

Options
d=db_name Store to the specified database.
i Store to individual databank files.
1/2 Store series in [single / double] precision to save space.
o Overwrite object in database (default is to merge data,
where possible).
g=arg Group store from workfile to database: “s” (copy group
definition and series as separate objects), “t” (copy group
definition and series as one object), “d” (copy series only
as separate objects), “l” (copy group definition only).

If you do not specify the precision option (1 or 2), the global option setting will be used. See
“Database Storage Defaults” on page 2551 of User’s Guide II.

Examples
store m1 gdp unemp

stores the three objects M1, GDP, UNEMP in the default database.
store(d=us1) m1 gdp macro::unemp

stores M1 and GDP in the US1 database and UNEMP in the MACRO database.
store usdat::gdp macro::gdp

stores the same object GDP in two different databases USDAT and MACRO.
store(1) cons*

stores all objects with names starting with CONS in the default database. The “1” option
uses single precision to save space.
store(i) m1 c:\data\unemp

stores M1 and UNEMP in individual databank files.


602—Chapter 17.Command Reference

Cross-references
“Basic Data Handling” on page 129 of User’s Guide I discusses exporting data in other file
formats. See Chapter 10. “EViews Databases,” on page 333 of User’s Guide I for a discussion
of EViews databases and databank files.

For additional discussion of wildcards, see Appendix A. “Wildcards,” on page 1227 of User’s
Guide I.

See also fetch (p. 449) and copy (p. 411).

switchreg Interactive Use Commands

Estimate a switching regression model (simple exogenous or Markov).

Syntax
switchreg(options) dependent_var list_of_varying_regressors [ @nv list_of_nonvary-
ing_regressors ] [ @prv list_of_probability_regressors ]

List the switchreg keyword, followed by options, then the dependent variable and a list of
the regressors with regime-varying coefficients, following optionally by the keyword @nv
and a list of regressors with regime-invariant coefficients, and by the keyword @prv and a
list of regressors that enter into the transition probability specification.

The dependent variable in switchreg may not be an expression. Dynamics may be speci-
fied by including lags of the dependent variable as regressors, or by specifying AR errors
using the AR keyword. The latter incorporate mean adjusted lags of the form specified by the
“Hamilton-model.”

Options
type=arg Type of switching: simple exogenous (“simple”), Markov
(“markov”).
nstates=integer Number of regimes.
(default=2)
heterr Allow for heterogeneous error variances across regimes
fprobmat=arg Name of fixed transition probability matrix allows for fixing
specific elements of the time-invariant transition matrix.
Leave NAs in elements of the matrix to estimate. The
 i, j  element of the matrix corresponds to
P  st  j st – 1  i  .
switchreg—603

initprob=arg Method for determining initial Markov regime probabilities:


(default=“ergodic”) ergodic solution (“ergodic”), estimated parameter (“est”),
equal probabilities (“uniform”), user-specified probabilities
(“user”).
If “initprob=user” is specified, you will need to specify the
“userinit=” option.
userinit=arg Name of vector containing user-specified initial Markov
probabilities. The vector should have rows equal to the
number of states; we expand this to the size of the initial
lag state vector where necessary for AR specifications.
For use in specifications containing both the “type=mar-
kov” and “initprob=user” options.
startnum=arg Number of random starting values tried. The default is 0
(default=0 or 25) for user-supplied coefficients (option “s”) and 25 in all
other cases.

startiter=arg Number of iterations taken after each random start before


(default=10) comparing objective to determine final starting value.
searchnum=arg Number of post-estimation perturbed starting values tried.
(default=0)
searchstds=arg Number of standard deviations to use in perturbed starts (if
(default=1) “searchnum=”) is specified.
seed=positive_inte- Seed the random number generator.
ger from 0 to If not specified, EViews will seed random number genera-
2,147,483,647 tor with a single integer draw from the default global ran-
dom number generator.
rnd=arg Type of random number generator: improved Knuth gener-
(default=“kn” or ator (“kn”), improved Mersenne Twister (“mt”), Knuth’s
method previously set (1997) lagged Fibonacci generator used in EViews 4
using rndseed (“kn4”) L’Ecuyer’s (1999) combined multiple recursive
(p. 577) in the Com- generator (“le”), Matsumoto and Nishimura’s (1998)
mand and Program- Mersenne Twister used in EViews 4 (“mt4”).
ming Reference).

In addition to the specification options, there are options for estimation and covariance cal-
culation.
604—Chapter 17.Command Reference

Additional Options
optmethod = arg Optimization method: “bfgs” (BFGS); “newton” (Newton-
Raphson), “opg” or “bhhh” (OPG or BHHH), “legacy”
(EViews legacy).
BFGS is the default method.
optstep = arg Step method: “marquardt” (Marquardt); “dogleg” (Dog-
leg); “linesearch” (Line search).
Marquardt is the default method.
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
cov=arg Covariance method: “ordinary” (default method based on
inverse of the estimated information matrix), “huber” or
“white” (Huber-White sandwich method).
covinfo = arg Information matrix method: “opg” (OPG); “hessian”
(observed Hessian).
(Applicable when non-legacy “optmethod=”.)
nodf Do not degree-of-freedom correct the coefficient covariance
estimate.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
s Use the current coefficient values in “C” as starting values
(see also param (p. 564) of the Command and Program-
ming Reference).
s=number Specify a number between zero and one to determine start-
ing values as a fraction of EViews default values (out of
range values are set to “s=1”).
showopts / -showopts [Do / do not] display the starting coefficient values and
estimation options in the estimation output.
prompt Force the dialog to appear from within a program.
p Print results.

Examples
switchreg(type=markov) y c @nv ar(1) ar(2) ar(3) ar(4)
tabplace—605

estimates a Hamilton-type Markov switching regression model with four non-regime varying
autoregressive terms implying mean adjustment for the lagged endogenous.
switchreg(type=markov) y c @nv y(-1) y(-2) y(-3) y(-4)

specifies an alternate dynamic model in which the lags enter directly into the contemporane-
ous equation without mean adjustment.
switchreg(type=markov) yy_dalt c @nv ar(1) ar(2) ar(3) ar(4) @prv c
yy_ldalt

estimates a 2 state model with non-varying AR(4) and transition matrix probability regressor
YY_LDALT.

Cross-references
See Chapter 39. “Switching Regression,” beginning on page 1677 of User’s Guide II for a
description of the switching regression methodology.

See also Equation::rgmprobs (p. 232), Equation::transprobs (p. 252), Equa-


tion::makergmprobs (p. 198) and Equation::maketransprobs (p. 199), all in the
Object Reference, for routines that allow you to work with the regime probabilities and tran-
sition probabilities.

tabplace Table Commands

Copies a portion of one table to the specified location in another table.

Syntax
tabplace(desttable,sourcetable,d1,s1,s2)
tabplace(desttable,sourcetable,dr1,dc1,sr1,sc1,sr2,sc2)

The tabplace command can be specified either using coordinates where columns are signi-
fied with a letter, and rows by a number (for example “A3” represents the first column, third
row), or by row number and column number.

The first syntax represents coordinate form, where sourcetable is the name of the table from
which to copy, s1 specifies the upper-left coordinate portion of the section of the source
table to be copied, s2 specifies the bottom-right coordinate, desttable specifies the name of
the table to copy to, and d1 specifies the upper-left coordinate of the destination table.

The second syntax represents the row/column number form, where sourcetable is the name
of the table from which to copy, sr1 specifies the source table upper row number, sc1 speci-
fies the source table left most column number, sr2 specifies the source table bottom row
number, sc2 specifies the source table right most column number. desttable specifies the
606—Chapter 17.Command Reference

name of the table to copy to, and dr1 and dr2 specify the upper and left most row and col-
umn of the destination table, respectively.

Examples
tabplace(table2,table1,"d1","B9","E17")

places a copy of the data from cell range B9 to E17 in TABLE1 to TABLE2 at cell D1
tabplace(table3,table1,10,3,9,2,17,5)

copies 8 rows of data (from row 9 to row 17) and 3 columns (from 2 to 5)of data in TABLE1
to the tenth row and 3rd column of TABLE3.

Cross-references
See also Table::copytable (p. 1078).

For additional discussion of table commands see Chapter 3. “Working with Tables and
Spreadsheets,” on page 57 of the Command and Programming Reference.

See also Chapter 17. “Table and Text Objects,” on page 937 of User’s Guide I for a discussion
and examples of table formatting in EViews.

testadd Interactive Use Commands

Test whether to add regressors to an estimated equation.

Tests the hypothesis that the listed variables were incorrectly omitted from an estimated
equation (only available for equations estimated by list). The test displays some combina-
tion of Wald and LR test statistics, as well as the auxiliary regression.

Syntax
testadd(options) arg1 [arg2 arg3 ...]

List the names of the series or groups of series to test for omission after the keyword. The
test is applied to the default equation, if defined.

Options
prompt Force the dialog to appear from within a program.
p Print output from the test.

Examples
ls sales c adver lsales ar(1)
testadd gdp gdp(-1)

tests whether GDP and GDP(-1) belong in the specification for SALES. The commands:
threshold—607

Cross-references
See “Coefficient Diagnostics” on page 1209 of User’s Guide II for further discussion.

See also testdrop (p. 607).

testdrop Interactive Use Commands

Test whether to drop regressors from a regression.

Tests the hypothesis that the listed variables were incorrectly included in the estimated
equation (only available for equations estimated by list). The test displays some combina-
tion of F and LR test statistics, as well as the test regression.

Syntax
testdrop(options) arg1 [arg2 arg3 ...]

List the names of the series or groups of series to test for omission after the keyword. The
test is applied to the default equation, if defined.

Options
prompt Force the dialog to appear from within a program.
p Print output from the test.

Examples
ls sales c adver lsales ar(1)
testdrop adver

tests whether ADVER should be excluded from the specification for SALES. The commands:

Cross-references
See “Coefficient Diagnostics” on page 1209 of User’s Guide II for further discussion of testing
coefficients.

See also testadd (p. 606) and Equation::wald (p. 267) in Object Reference.

threshold Interactive Use Commands

Estimation by discrete or smooth threshold least squares, including threshold autoregres-


sion.

Syntax
threshold(options) y z1 [z2 z3 ...] [@nv x1 x2 x3 ...] @thresh t1 [t2 t3 ...]
608—Chapter 17.Command Reference

List the dependent variable first, followed by a list of the independent variables that have
coefficients that are allowed to vary across thresholds, followed optionally by the keyword
@nv and a list of non-varying coefficient variables.

List a threshold variable or variables (for model selection) or a single integer or range pairs
after the keyword @thresh. The integer or range pairs indicate a self-exciting model with the
lagged dependent variable as the threshold variable.

For smooth threshold equations you may specify variables that are to be included only in the
base specification or only in the alternative specification. Base-only variables should be
specified in parentheses using the @base key, as in “@base(x1) @base(x2) @base(x3 x4)”.
Alternative-only variables may be specified analogously using the @alt key.

Options
Specification Options
type=arg Type of threshold estimation: “discrete” (discrete),
(default=“discrete”) “smooth” (smooth).

Discrete Threshold Options


method=arg Threshold selection method: “seqplus1” (sequential
(default=“seqplus1”) tests of single l  1 versus l thresholds), “seqall”
(sequential test of all possible l  1 versus l thresh-
olds), “glob” (tests of global l vs. no thresholds), “glob-
plus1” (tests of l  1 versus l globally determined
thresholds), “globinfo” (information criteria evalua-
tion)., “fixedseq” (fixed number of sequentially deter-
mined thresholds), “fixedglob” (fixed number of
globally determined thresholds), “user” (user-specified
thresholds)
nthresh=arg Number of thresholds for fixed number threshold selec-
(default=1) tion methods.
select=arg Sub-method setting (options depend on “method=”).
(1) if “method=glob”: Sequential ("seq") (default),
Highest significant ("high"), UDmax ("udmax"),
WDmax ("wdmax").
(2) if “method=globinfo”: Schwarz criterion (“bic” or
“sic”) (default), Liu-Wu-Zidek criterion (“lwz”).
trim=arg (default=5) Trimming percentage for determining minimum segment
size (5, 10, 15, 20, 25).
maxthresh=integer Maximum number of thresholds to allow (not applicable
(default=5) if “method=seqall”).
threshold—609

maxlevels=integer Maximum number of threshold levels to consider in


(default=5) sequential testing (applicable when
“method=sequall”).
size=arg (default=5) Test sizes for use in sequential determination and final
test evaluation (10, 5, 2.5, 1) corresponding to 0.10,
0.05, 0.025, 0.01, respectively
heterr Assume regimes specific error distributions in variance
computation.
commondata Assume a common distribution for the data across seg-
ments (only applicable if original equation is estimated
with a robust covariance method, “heterr” is not speci-
fied).

Smooth Threshold Options


smoothtrans=arg Smooth threshold transition function: “logistic” (logis-
(default=“logistic”) tic), “logistic2” (second-order logistic), “exponential”
(exponential), “normal” (normal).
smoothstart=arg Smoth threshold starting value method: or fixed number
(default=“grid_conc” threshold selection methods: “grid_conc” (grid search
) with concentrated regression coefficients”, “grid_zeros”
(grid search with zero regression coefficients), “data”
(data-based), “user” (user-specified using the contents
of the coefficient vector in the workfile).
smoothst=arg Sub-method setting (options depend on “method=”).
(1) if “method=glob”: Sequential ("seq") (default),
Highest significant ("high"), UDmax ("udmax"),
WDmax ("wdmax").
(2) if “method=globinfo”: Schwarz criterion (“bic” or
“sic”) (default), Liu-Wu-Zidek criterion (“lwz”).

General Options
w=arg Weight series or expression.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
cov=keyword Covariance type (optional): “white” (White diagonal
matrix), “hac” (Newey-West HAC).
610—Chapter 17.Command Reference

nodf Do not perform degree of freedom corrections in computing


coefficient covariance matrix. The default is to use degree
of freedom corrections.
covlag=arg Whitening lag specification: integer (user-specified lag
(default=1) value), “a” (automatic selection).
covinfosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
covmaxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum
13
of T .
covkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
covbw=arg Kernel Bandwidth: “fixednw” (Newey-West fixed),
(default=“fixednw” “andrews” (Andrews automatic), “neweywest” (Newey-
) West automatic), number (User-specified bandwidth).
covnwlag=integer Newey-West lag-selection parameter for use in nonpara-
metric kernel bandwidth selection (if “covbw=newey-
west”).
covbwint Use integer portion of bandwidth.
prompt Force the dialog to appear from within a program.
p Print basic estimation results.

Examples
threshold(method=fixedseq, type=discrete) ss_transf c ss_transf(-1
to -11) @thresh 2

uses the fixed number of thresholds test to determine the optimal threshold in a model
regressing SS_TRANSF on the threshold variables C and SS_TRANSF(-1 to -11).
threshold(method=fixedseq, type=discrete) ss_transf c ss_transf(-1
to -11) @thresh 1 5

uses the fixed number of thresholds test to determine the optimal threshold and does model
selection over lags of SS_TRANSF from SS_TRANSF(-1) to SS_TRANSF(-5).
threshold(method=user, threshold=7.44) ss_transf c @nv ss_transf(-
1 to -11) @thresh 2
toc—611

estimates the model with one user-specified threshold value. In addition, the variables
SS_TRANSF(-1 to -11) are restricted to have common coefficients across the regimes.

Cross-references
See Chapter 35. “Discrete Threshold Regression,” on page 1561 for a discussion of the vari-
ous forms of threshold models.

tic Programming Commands

Reset the timer.

Syntax
Command: tic

Examples
The sequence of commands:
tic
[some commands]
toc

resets the timer, executes commands, and then displays the elapsed time in the status line.
Alternatively:
tic
[some commands]
!elapsed = @toc

resets the time, executes commands, and saves the elapsed time in the control variable
!ELAPSED.

Cross-references
See also toc (p. 611) and @toc (p. 1146).

toc Programming Commands

Display elapsed time (since timer reset) in seconds.

Syntax
Command: toc

Examples
The sequence of commands:
612—Chapter 17.Command Reference

tic
[some commands]
toc

resets the timer, executes commands, and then displays the elapsed time in the status line.
The set of commands:
tic
[some commands]
!elapsed = @toc
[more commands]
toc

resets the time, executes commands, saves the elapsed time in the control variable
!ELAPSED, executes additional commands, and displays the total elapsed time in the status
line.

Cross-references
See also tic (p. 611), toc (p. 611), and @toc (p. 1146).

tsls Interactive Use Commands

Two-stage least squares.

Carries out estimation using two-stage least squares.

Syntax
tsls(options) y x1 [x2 x3 ...] @ z1 [z2 z3 ...]
tsls(options) specification @ z1 [z2 z3 ...]

To use the tsls command, list the dependent variable first, followed by the regressors, then
any AR or MA error specifications, then an “@”-sign, and finally, a list of exogenous instru-
ments. You may estimate nonlinear equations or equations specified with formulas by first
providing a specification, then listing the instrumental variables after an “@”-sign.

There must be at least as many instrumental variables as there are independent variables.
All exogenous variables included in the regressor list should also be included in the instru-
ment list. A constant is included in the list of instrumental variables even if not explicitly
specified.
tsls—613

Options
Non-Panel TSLS Options
nocinst Do not automatically include a constant as an instrument.
w=arg Weight series or expression.
Note: we recommend that, absent a good reason, you
employ the default settings Inverse std. dev. weights
(“wtype=istdev”) with EViews default scaling
(“wscale=eviews”) for backward compatibility with ver-
sions prior to EViews 7.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
z Turn off backcasting in ARMA models.
cov=keyword Covariance type (optional): “white” (White diagonal
matrix), “hac” (Newey-West HAC).
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
covlag=arg Whitening lag specification: integer (user-specified lag
(default=1) value), “a” (automatic selection).
covinfosel=arg Information criterion for automatic selection: “aic”
(default=“aic”) (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn) (if
“lag=a”).
covmaxlag=integer Maximum lag-length for automatic selection (optional) (if
“lag=a”). The default is an observation-based maximum
13
of T .
covkern=arg Kernel shape: “none” (no kernel), “bart” (Bartlett, default),
(default=“bart”) “bohman” (Bohman), “daniell” (Daniel), “parzen”
(Parzen), “parzriesz” (Parzen-Riesz), “parzgeo” (Parzen-
Geometric), “parzcauchy” (Parzen-Cauchy), “quadspec”
(Quadratic Spectral), “trunc” (Truncated), “thamm”
(Tukey-Hamming), “thann” (Tukey-Hanning), “tparz”
(Tukey-Parzen).
covbw=arg Kernel Bandwidth: “fixednw” (Newey-West fixed),
(default=“fixednw” “andrews” (Andrews automatic), “neweywest” (Newey-
) West automatic), number (User-specified bandwidth).
614—Chapter 17.Command Reference

covnwlag=integer Newey-West lag-selection parameter for use in nonpara-


metric kernel bandwidth selection (if “covbw=newey-
west”).
covbwint Use integer portion of bandwidth.
m=integer Set maximum number of iterations.
c=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
s Use the current coefficient values in estimator coefficient
vector as starting values for equations specified by list with
AR or MA terms (see also param (p. 564) of the Com-
mand and Programming Reference).
s=number Determine starting values for equations specified by list
with AR or MA terms. Specify a number between zero and
one representing the fraction of TSLS estimates computed
without AR or MA terms to be used. Note that out of range
values are set to “s=1”. Specifying “s=0” initializes coeffi-
cients to zero. By default EViews uses “s=1”.
Does not apply to coefficients for AR and MA terms which
are set to EViews determined default values.
numericderiv / [Do / do not] use numeric derivatives only. If omitted,
-numericderiv EViews will follow the global default.
fastderiv / -fastderiv [Do / do not] use fast derivative computation. If omitted,
EViews will follow the global default.
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print basic estimation results.
tsls—615

Panel TSLS Options


cx=arg Cross-section effects. For fixed effects estimation, use
“cx=f”; for random effects estimation, use “cx=r”.
per=arg Period effects. For fixed effects estimation, use “cx=f”; for
random effects estimation, use “cx=r”.
wgt=arg GLS weighting: (default) none, cross-section system
weights (“wgt=cxsur”), period system weights
(“wgt=persur”), cross-section diagonal weighs
(“wgt=cxdiag”), period diagonal weights (“wgt=per-
diag”).
cov=arg Coefficient covariance method: (default) ordinary, White
cross-section system robust (“cov=cxwhite”), White
period system robust (“cov=perwhite”), White heteroske-
dasticity robust (“cov=stackedwhite”), Cross-section sys-
tem robust/PCSE (“cov=cxsur”), Period system
robust/PCSE (“cov=persur”), Cross-section heteroskedas-
ticity robust/PCSE (“cov=cxdiag”), Period heteroskedastic-
ity robust (“cov=perdiag”).
keepwgts Keep full set of GLS weights used in estimation with object,
if applicable (by default, only small memory weights are
saved).
rancalc=arg Random component method: Swamy-Arora (“ran-
(default=“sa”) calc=sa”), Wansbeek-Kapteyn (“rancalc=wk”), Wallace-
Hussain (“rancalc=wh”).
nodf Do not perform degree of freedom corrections in computing
coefficient covariance matrix. The default is to use degree
of freedom corrections.
iter=arg Iteration control for GLS specifications: perform one weight
(default=“onec”) iteration, then iterate coefficients to convergence
(“iter=onec”), iterate weights and coefficients simultane-
ously to convergence (“iter=sim”), iterate weights and
coefficients sequentially to convergence (“iter=seq”), per-
form one weight iteration, then one coefficient step
(“iter=oneb”).
Note that random effects models currently do not permit
weight iteration to convergence.
unbalsur Compute SUR factorization in unbalanced data using the
subset of available observations for a cluster.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default is to use the “C” coefficient vector.
616—Chapter 17.Command Reference

s Use the current coefficient values in estimator coefficient


vector as starting values for equations specified by list with
AR terms (see also param (p. 564) of the Command and
Programming Reference).
s=number Determine starting values for equations specified by list
with AR terms. Specify a number between zero and one
representing the fraction of TSLS estimates computed with-
out AR terms to be used. Note that out of range values are
set to “s=1”. Specifying “s=0” initializes coefficients to
zero. By default EViews uses “s=1”.
Does not apply to coefficients for AR terms which are
instead set to EViews determined default values.
m=integer Set maximum number of iterations.
c=number Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled coeffi-
cients. The criterion will be set to the nearest value
between 1e-24 and 0.2.
numericderiv / [Do / do not] use numeric derivatives only. If omitted,
-numericderiv EViews will follow the global default.
fastderiv / -fastderiv [Do / do not] use fast derivative computation. If omitted,
EViews will follow the global default.
showopts / [Do / do not] display the starting coefficient values and
-showopts estimation options in the estimation output.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Examples
tsls y_d c cpi inc ar(1) @ lw(-1 to -3)

estimates an UNTITLED equation using TSLS regression of Y_D on a constant, CPI, INC with
AR(1) using a constant, LW(-1), LW(-2), and LW(-3) as instruments.
param c(1) .1 c(2) .1
tsls(s,m=500) y_d=c(1)+inc^c(2) @ cpi

estimates a nonlinear TSLS model using a constant and CPI as instruments. The first line
sets the starting values for the nonlinear iteration algorithm.

Cross-references
See Chapter 21. “Additional Regression Tools,” on page 1029 and “Two-Stage Least Squares”
on page 1905 of User’s Guide II for details on two-stage least squares estimation in single
equations and systems, respectively. “Instrumental Variables” on page 2297 of User’s Guide
ttom—617

II discusses estimation using pool objects, while “Instrumental Variables Estimation” on


page 2330 of User’s Guide II discusses estimation in panel structured workfiles.

See also ls (p. 510).

ttom Matrix Utility Commands

Convert table to matrix object.

Table-TO-Matrix Object: fills the matrix, m1, with the numeric values contained in the table
o1. m1 will be resized appropriately. o1 may be a table object in the current workfile, or an
object view command that creates a table view from an object.

Syntax
ttom(o1, o2[, range="cell_range", keepna])

where o1 is a table object in the current workfile, or an object view command that creates a
table view from an object, o2 is a corresponding vector, svector, or matrix, range is an
optional range of cells, and a non-zero value for keepna may be used to indicate that miss-
ing values should be retained. By default any row or column of the table that does not con-
tain numbers will be dropped from the matrix.

If the “range=” option is provided, a subset of the cells of the table will be converted,
where cell_range can take one of the following forms:
@all Apply to all cells in the table.
cell Cell identifier. You can identify cells using either the col-
umn letter and row number (e.g., “A1”), or by using “R”
followed by the row number followed by “C” and the col-
umn number (e.g., “R1C2”).
row[,] col Row number, followed by column letter or number (e.g.,
“2,C”, or “2,3”), separated by “,”. Apply to cell.
row Row number (e.g., “2”). Apply to all cells in the row.
col Column letter (e.g., “B”). Apply to all cells in the column.
618—Chapter 17.Command Reference

first_cell[:]last_cell, Top left cell of the selection range (specified in “cell” for-
first_cell[,]last_cell mat), followed by bottom right cell of the selection range
(specified in “cell” format), separated by a “:” or “,” (e.g.,
“A2:C10”, “A2,C10”, or “R2C1:R10C3”, “R2C1,R10C3”).
Apply to all cells in the rectangular region defined by the
first cell and last cell.
first_cell_row[,] Top left cell of the selection range (specified in “row[,] col”
first_cell_col[,] last_- format), followed by bottom right cell of the selection
cell_row[,] last_- range (specified in “row[,] col” format), separated by a “,”
cell_col (e.g., “2,A,10,C” or “2,1,10,3”). Apply to all cells in the
rectangular region defined by the first cell and last cell.

Examples
ttom(table1,matrix1)

Creates a matrix object, MATRIX1, containing the numerical data in the table object
TABLE1. Any row or column of the table that contains no numbers (i.e. are blank rows/col-
umns, or only contain text) are skipped in the conversion process.
ttom(table1, matrix1, keepna)

Performs the same conversion, but this time any row or column of the table that contains no
numbers are included in the conversion process as a row/column of NAs.
ttom(eq01.wald c(1)=0.3, matrix1)

Performs a Wald test of the restriction C(1)=0.3 from the EQ01, and saves the numerical
output from that test in to the matrix object MATRIX1.

Cross-references
See also mtos (p. 522), @convert (p. 764), stom (p. 598), and stomna (p. 599).

unlink Object Container, Data, and File Commands

Break links and auto-updating series (formulae) in the specified series objects.

Syntax
unlink link_names

unlink converts link objects and auto-updating series to ordinary series or alphas. Follow
the keyword with a list of names of links and auto-updating series to be converted to ordi-
nary series (values). The list of links may include wildcard characters.

Examples
unlink gdp income
uroot—619

converts the link series GDP and INCOME to ordinary series.


unlink *

breaks all links in the active workfile page.

Cross-references
See Chapter 8. “Series Links,” on page 249 of User’s Guide I for a description of link objects,
and “Auto-Updating Series” on page 219 of User’s Guide I for a discussion of auto-updating
series. See also Link::link (p. 530) and Link::linkto (p. 530).

See also pageunlink (p. 561) and wfunlink (p. 664) for page and workfile based unlink-
ing, respectively.

uroot Interactive Use Commands

Carries out unit root tests on a series or panel structured series.

For ordinary series, computes conventional Augmented Dickey-Fuller (ADF), GLS detrended
Dickey-Fuller (DFGLS), Phillips-Perron (PP), Kwiatkowski, et. al. (KPSS), Elliot, Rothenberg,
and Stock (ERS) Point Optimal, or Ng and Perron (NP) tests for a unit root in the series or its
first or second difference.

For series in a panel structured workfile, computes Levin, Lin and Chu (LLC), Breitung, Im,
Pesaran, and Shin (IPS), Fisher - ADF, Fisher - PP, or Hadri panel unit root tests on levels,
first, or second differences of the data.

Syntax
uroot(options) series_name

There are different options for conventional tests on an ordinary series and panel tests for
series in panel structured workfiles.

Options for Conventional Unit Root Tests


Basic Specification
You should specify the exogenous variables and order of dependent variable differencing in
the test equation using the following options:
exog=arg Specification of exogenous trend variables in the test equa-
(default=“const”) tion: “const” “trend” (include a constant and a linear time
trend), “none” (do not include any exogenous regressors).
dif=integer Order of differencing of the series prior to running the test.
(default=0) Valid values are {0, 1, 2}.

You should specify the test type using one of the following keywords:
620—Chapter 17.Command Reference

adf (default) Augmented Dickey-Fuller.


dfgls GLS detrended Dickey-Fuller (Elliot, Rothenberg, and
Stock).
pp Phillips-Perron.
kpss Kwiatkowski, Phillips, Schmidt, and Shin.
ers Elliot, Rothenberg, and Stock (Point Optimal).
np Ng and Perron.

Note that for backward compatibility, EViews supports older forms of the exogenous specifi-
cation:
const, c (default) Include a constant in the test equation.
trend, t Include a constant and a linear time trend in the test equa-
tion.
none, n Do not include a constant or time trend (only available for
the ADF and PP tests).

For future compatibility we recommend that you use the “exog=” format.
Spectral Estimation Option
In addition, PP, KPSS, ERS, and NP tests all require the estimation of the long-run variance
(frequency zero spectrum). You may specify the method using the “hac=” option. The
default setting depends on the selected test.
hac=arg Method of estimating the frequency zero spectrum: “bt”
(default=varies) (Bartlett kernel), “pr” (Parzen kernel), “qs” (Quadratic
Spectral kernel), “ar” (AR spectral), “ardt (AR spectral -
OLS detrended data), “argls” (AR spectral - GLS detrended
data).
The default settings are test specific (“bt” for PP and KPSS
tests, “ar” for ERS, “argls” for NP).

Lag Difference Options


Applicable to ADF and DFGLS tests, and for PP, KPSS, ERS, and NP tests that use a AR spec-
tral density estimator (“hac=ar”, “hac=ardt”, or “hac=argls”). The default lag selection
method is based on a comparison of Schwarz criterion values. You may specify a fixed lag
using the “lag=” option.
uroot—621

lagmethod=arg Method for selecting lag length (number of first difference


(default=“sic”) terms) to be included in the Dickey-Fuller test regression or
number of lags in the AR spectral density estimator:
“aic” (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn),
“msaic” (Modified Akaike), “msic” (Modified Schwarz),
“mhqc” (Modified Hannan-Quinn), “tstat” (Ng-Perron first
backward significant t-statistic).
lag=integer Use-specified fixed lag.
maxlag=integer Maximum lag length to consider when performing auto-
matic lag length selection.
0.25
default= int( 12T  100  )
lagpval=arg Probability value for use in the t-statistic automatic lag
(default=0.1) selection method (“lagmethod = tstat”).

Kernel Option
Applicable to PP, KPSS, ERS, and NP tests when using kernel estimators of the frequency
zero spectrum (where “hac=bt”, “hac=pz”, or “hac=qs”)
band = arg, b=arg Method of selecting the bandwidth: “nw” (Newey-West
(default=“nw”) automatic variable bandwidth selection), “a” (Andrews
automatic selection), number (user specified bandwidth).

General Options
prompt Force the dialog to appear from within a program.
p Print output from the test.

Options for Panel Unit Root Tests


Basic Specification
You should specify the exogenous variables, order of dependent variable differencing, and
sample handling, in the test equation using the following options:
exog=arg Specification of exogenous trend variables in the test equa-
(default=“const”) tion: “const” (constant),“trend” (include a constant and a
linear time trend), “none” (do not include exogenous
regressors).
dif=integer Order of differencing of the series prior to running the test.
(default=0) Valid values are {0, 1, 2}.
balance Use balanced (across cross-sections or series) data when
performing test.
622—Chapter 17.Command Reference

You may use one of the following keywords to specify the test:
sum (default) Summary of all of the panel unit root tests.
llc Levin, Lin, and Chu.
breit Breitung.
ips Im, Pesaran, and Shin.
adf Fisher - ADF.
pp Fisher - PP.
hadri Hadri.

For backward compatibility, EViews supports older forms of the exogenous specification:
const, c (default) Include a constant in the test equation.
trend, t Include a constant and a linear time trend in the test equa-
tion.
none, n Do not include a constant or time trend (only available for
the ADF and PP tests).

For future compatibility we recommend that you use the “exog=” format.
Lag Difference Options
Specifies the number of lag difference terms to be included in the test equation. Applicable
in “Summary”, LLC, Breitung, IPS, and Fisher-ADF tests. The default setting is to perform
automatic lag selection using the Schwarz criteria (“lagmethod=sic”).
lagmethod=arg Method for selecting lag lengths (number of first difference
(default=“sic”) terms) to be included in the Dickey-Fuller test regressions:
“aic” (Akaike), “sic” (Schwarz), “hqc” (Hannan-Quinn),
“tstat” (Ng-Perron first backward significant t-statistic).
uroot—623

lag=arg Specified lag length (number of first difference terms) to be


included in the regression: integer (user-specified common
lag length), vector_name (user-specific individual lag
length, one row per cross-section).
maxlag=arg Maximum lag length to consider when performing auto-
matic lag length selection: integer (common maximum lag
length), or vector_name (individual maximum lag length,
one row per cross-section). The default setting produces
individual maximum lags of,
14
default= int(min(12, T i  3)   T i  100  )
where T i is the length of the cross-section.
lagpval=arg Probability value for use in the t-statistic automatic lag
(default=0.1) selection method (when “lagmethod = tstat”).

Kernel Options
Specifies options for computing kernel estimates of the zero-frequency spectrum (long-run
covariance). Applicable to “Summary”, LLC, Fisher-PP, and Hadri tests.
hac=arg Method of estimating the frequency zero spectrum: “bt”
(default=“bt”) (Bartlett kernel), “pr” (Parzen kernel), “qs” (Quadratic
Spectral kernel),
band = arg, b=arg Method of selecting the bandwidth: “nw” (Newey-West
(default=“nw”) automatic variable bandwidth selection), “a” (Andrews
automatic selection), number (user-specified common
bandwidth), vector_name (user-specified individual band-
widths, one row for each cross-section).

General options
prompt Force the dialog to appear from within a program.
p Print output from the test.

Examples
The command:
uroot(adf,const,lag=3,save=mout) gdp

performs an ADF test on the series GDP with the test equation including a constant term
and three lagged first-difference terms. Intermediate results are stored in the matrix MOUT.
uroot(dfgls,trend,infosel=sic) ip

runs the DFGLS unit root test on the series IP with a constant and a trend. The number of
lagged difference terms is selected automatically using the Schwarz criterion.
624—Chapter 17.Command Reference

uroot(kpss,const,hac=pr,b=2.3) unemp

runs the KPSS test on the series UNEMP. The null hypothesis is that the series is stationary
around a constant mean. The frequency zero spectrum is estimated using kernel methods
(with a Parzen kernel), and a bandwidth of 2.3.
uroot(np,hac=ardt,infosel=maic) sp500

runs the NP test on the series SP500. The frequency zero spectrum is estimated using the
OLS AR spectral estimator with the lag length automatically selected using the modified
AIC.

Cross-references
See “Unit Root Testing” on page 1779 of User’s Guide II for discussion of standard unit root
tests performed on a single series, “Cross-sectionally Independent Panel Unit Root Testing”
on page 1817 of User’s Guide II for discussion of unit roots tests performed on panel struc-
tured workfiles, groups of series, or pooled data.

varest Interactive Use Commands

Specify and estimate a VAR or VEC.

Syntax
varest(options) lag_pairs endog_list [@ exog_list]
varest(method=ec, trend, n, options) lag_pairs endog_list [@ exog_list]

The first form of the command estimates a VAR. It is the interactive command equivalent of
using ls to estimate a named VAR object (see Var::ls (p. 1185) in the Object Reference for
syntax and details).

The second form of the command estimates a VEC. It is the interactive command equivalent
of using ec to estimate a named VAR object (see Var::ec (p. 1163) in the Object Reference
for syntax and details).

Examples
prompt Force the dialog to appear from within a program.
p Print output from the test.

Examples
varest 1 3 m1 gdp

estimates an unnamed unrestricted VAR with two endogenous variables (M1 and GDP), a
constant and 3 lags (lags 1 through 3).
varsel—625

varest(noconst) 1 3 ml gdp

estimates the same VAR, but with no constant term included in the specification.
varest(method=ec) 1 4 m1 gdp tb3

estimates a VEC with four lagged first differences, three endogenous variables and one
cointegrating equation using the default trend option “c”.
varest(method=ec,b,2) 1 2 4 4 tb1 tb3 tb6 @ d2 d3 d4

estimates a VEC with lagged first differences of order 1, 2, 4, three endogenous variables,
three exogenous variables, and two cointegrating equations using trend option “b”.

Cross-references
See also Var::var (p. 1214), Var::ls (p. 1185) and Var::ec (p. 1163) in the Object Refer-
ence.

varsel Interactive Use Commands

Estimation using variable selection.

Syntax
varsel(options) y x1 [x2 x3 ...] @ z1 z2 z3

Specify the dependent variable followed by a list of variables to be included in the regres-
sion, but not part of the search routine, followed by an “@” symbol and a list of variables to
be part of the search routine. If no included variables are required, simply follow the depen-
dent variable with an “@” symbol and the list of search variables.

Options
method = arg Stepwise regression method: “stepwise” (default), “uni”
(uni-directional), “swap” (swapwise), “comb” (combinato-
rial), “gets” (auto-search/GETS), “lasso” (Lasso).
nvars = int Set the number of search regressors. Required for swapwise
and combinatorial methods, optional for uni-directional
and stepwise methods.
w=arg Weight series or expression.
Note: we recommend that, absent a good reason, you
employ the default settings Inverse std. dev. weights
(“wtype=istdev”) with EViews default scaling
(“wscale=eviews”) for backward compatibility with ver-
sions prior to EViews 7.
626—Chapter 17.Command Reference

wtype=arg Weight specification type: inverse standard deviation (“ist-


(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wscale=arg Weight scaling: EViews default (“eviews”), average
(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Stepwise and uni-directional method options


back Set stepwise or uni-directional method to run backward. If
omitted, the method runs forward.
tstat Use t-statistic values as a stopping criterion. (default uses
p-values).
ftol=number (default Set forward stopping criterion value.
= 0.5)
btol=number (default Set backward stopping criterion value.
= 0.5)
fmaxstep=int Set the maximum number of steps forward.
(default = 1000)
bmaxstep=int Set the maximum number of steps backward.
(default = 1000)
tmaxstep=int Set the maximum total number of steps.
(default = 2000)

Swapwise method options


minr2 Use minimum R-squared increments. (Default uses maxi-
mum R-squared increments.)

Combinatorial method options


force Suppress the warning message issued when a large number
of regressions will be performed.
varsel—627

Auto-search/GETS method options


pval=number Set the terminal condition p-value used to determine the
(default = 0.05) stopping point of each search path
nolm Do not perform AR LM diagnostic test.
arpval=number Set p-value used in AR LM diagnostic test.
(default = 0.025)
arlags=int (default = Set number of lags used in AR LM diagnostic test.
1)
noarch Do not perform ARCH LM diagnostic test.
archpval=number Set p-value used in ARCH LM diagnostic test.
(default = 0.025)
archlags=int (default Set number of lags used in ARCH LM diagnostic test.
= 1)
nojb Do not perform Jarque-Bera normality diagnostic test.
jbpval=number Set p-value used in Jarque-Bera normality diagnostic test.
(default = 0.025)
nopet Do not perform Parsimonious Encompassing diagnostic
test.
petpval=number Set p-value used in Parsimonious Encompassing diagnostic
(default = 0.025) test.
nogum Do not include the general model as a candidate for model
selection.
noempty Do not include the empty model as a candidate for model
selection.
ic =arg Set the information criterion used in model selection: “AIC”
(Akaike information criteria, default), “BIC” (Schwarz
information criteria), “HQ” (Hannan-Quin criteria).
blocks=int Override the EViews’ determination of the number of
blocks in which to split the estimation sample.
628—Chapter 17.Command Reference

Lasso method options


Penalty Options
ytrans=arg Scaling of the dependent variable: “none” (none), “L1”
(default=“none”) (L1), “L2” (L2), “stdsmpl” (sample standard deviation),
“stdpop” (population standard deviation), “minmax” (min-
max).
xtrans=arg Scaling of the regressor variables: “none” (none), “L1” (L1
(default=“stdpop”) norm), “L2” (L2 norm), “stdsmpl” (sample standard devia-
tion), “stdpop” (population standard deviation), “minmax”
(min-max).
lambda=arg Value of the penalty parameter. Can be a single number, list
of space-delimited numbers, a workfile series object, or left
blank for a EViews determined path (default). Values must
be zero or greater.
nlambdas=integer Number of penalty values for EViews-supplied list.
(default=100)
nlambdamin=integer Minimum number of lambda values in the path before
(default=5) applying stopping rules.
minddev=arg Minimum change in deviance fraction to continue estima-
(default=1e-05) tion. Truncate path estimation if relative change in devi-
ance is smaller than this value.
maxedev=arg Maximum of deviance explained fraction attained to termi-
(default=0.99) nate estimation. Truncate path estimation if fraction of null
deviance explained is larger than this value.
maxvars=arg Maximum number of regressors in the model. Truncate
path estimation if the number of coefficients (including
those for non-penalized variables like the intercept)
reaches this value.
maxvarsratio=arg Maximum number of regressors in the model as a fraction
of the number of observations. Truncate path estimation if
the number of coefficients (including those for non-penal-
ized variables like the intercept) divided by the number of
observations reaches this value.
varsel—629

Cross Validation Options


cvmethod=arg Cross-validation method: “kfold” (k-fold), “simple” (simple
(default=“kfold_cv”) split), “mcarlo” (Monte Carlo), “leavepout” (leave-P-out),
“leave1out” (leave-1-out), “rolling” (rolling window),
“expanding” (expanding window).
cvmeasure=arg Cross-validation fit measure: “mse” (mean-squared error),
(default=“mse”) “r2” (R-squared), “mae” (mean absolute error), “mape”
(mean absolute percentage error), “smape” (symmetric
mean absolute percentage error).
cvnfolds=arg Number of folds for K-fold cross-validation.
(default=5) For “cvmethod=kfold”.
cvftrain=arg Proportion of data for split and Monte Carlo methods.
(default=0.8) For “cvmethod=simple” and “cvmethod=mcarlo”.
cvnreps=arg Number of Monte Carlo method repetitions.
(default=1) For “cvmethod=mcarlo”.
cvleaveout=arg Number of data points left out for leave-p-out method.
(default=2) For “cvmethod=leavepout”.
cvnwindows=arg Number of windows for rolling window cross-validation
(default=4) method.
For “cvmethod=rolling”.
cvinitial=arg Number of initial data points in the training set for expand-
(default=12) ing cross-validation.
For “cvmethod=expanding”.
cvpregap=arg Number of observations between end of training set and
(default=0) beginning of test set.
For “cvmethod=simple”, “cvmethod=rolling” and
“cvmethod=expanding”.
cvhorizon=arg Number of observation in the test set.
(default=1) For “cvmethod=rolling” and “cvmethod=expanding”.
cvpostgap=arg Number of observations between end of test set and begin-
(default=0) ning of next training set for rolling window or between end
of test set and end of next training set for expanding win-
dow.
For “cvmethod=rolling” and “cvmethod=expanding”
630—Chapter 17.Command Reference

Random Number Options


seed=positive_inte- Seed the random number generator.
ger from 0 to If not specified, EViews will seed random number genera-
2,147,483,647 tor with a single integer draw from the default global ran-
dom number generator.
rnd=arg Type of random number generator: improved Knuth gener-
(default=“kn” or ator (“kn”), improved Mersenne Twister (“mt”), Knuth’s
method previously set (1997) lagged Fibonacci generator used in EViews 4
using rndseed (“kn4”) L’Ecuyer’s (1999) combined multiple recursive
(p. 577)). generator (“le”), Matsumoto and Nishimura’s (1998)
Mersenne Twister used in EViews 4 (“mt4”).

Other Options
coefmin= Vector of individual coefficient minimum values, contain-
vector_name, number ing negative or missing values sized to and matching the
order of the variables in the specification, or a negative
value for the minimum for all coefficients.
Missing values in the vector should be used to indicate that
the coefficient is unrestricted.
If a vector of values is provided and individual minimums
are specified using one or more @vw regressors, the vector
values will be applied first, then overwritten by the individ-
ual values.
coefmax= Vector of individual coefficient maximum values, contain-
vector_name, number ing positive or missing values sized to and matching the
order of the variables in the specification, or a positive
value for the maximum for all coefficients.
Missing values in the vector should be used to indicate that
the coefficient is unrestricted.
If a vector of values is provided and individual maximums
are specified using one or more @vw regressors, the vector
values will be applied first, then overwritten by the individ-
ual values.
maxit=integer Maximum number of iterations.
conv=scalar Set convergence criterion. The criterion is based upon the
maximum of the percentage changes in the scaled esti-
mates. The criterion will be set to the nearest value
between 1e-24 and 0.2.
w=arg Weight series or expression.
wtype=arg Weight specification type: inverse standard deviation (“ist-
(default=“istdev”) dev”), inverse variance (“ivar”), standard deviation
(“stdev”), variance (“var”).
wfclose—631

wscale=arg Weight scaling: EViews default (“eviews”), average


(“avg”), none (“none”).
The default setting depends upon the weight type:
“eviews” if “wtype=istdev”, “avg” for all others.
coef=arg Specify the name of the coefficient vector (if specified by
list); the default behavior is to use the “C” coefficient vec-
tor.
showopts / -showopts [Do / do not] display the starting coefficient values and
estimation options in the rotation output.
prompt Force the dialog to appear from within a program.
p Print estimation results.

Examples
varsel(method=comb,nvars=3) y c @ x1 x2 x3 x4 x5 x6 x7 x8

performs a combinatorial search routine to search for the three variables from the set of X1,
X2, ..., X8, yielding the largest R-squared in a regression of Y on a constant and those three
variables.

Cross-references
See Chapter 22. “Regression Variable Selection,” on page 1071 of User’s Guide II for exten-
sive discussion.

wfclose Object Container, Data, and File Commands

Close the active or specified workfile.

Syntax
wfclose(options) [name]

wfclose allows you to close the currently active workfile. You may optionally provide the
name of a workfile if you do not wish to close the active workfile. If more than one workfile
is found with the same name, the one most recently opened will be closed.

Options
noerr Do not error if a name is provided and no workfile with
that name is found.

Examples
wfclose
632—Chapter 17.Command Reference

closes the workfile that was most recently active.


wfclose basics

closes the workfile named BASICS.

Cross-references
See also wfcreate (p. 634), wfopen (p. 640) and wfsave (p. 656).

wfcompare Object Container, Data, and File Commands

Compare the contents of the current workfile or page with the contents of a different work-
file, page or database.

Syntax
wfcompare(options) targetspec baselinespec [@keep keeplist @drop droplist]

The command shows a list of any differences between the objects specified by targetspec
and those specified by baselinespec.

targetspec should be a specification of objects in the current workfile. It should take the form
of [page\]name_pattern, where the optional page\ may be used to specify a specific page of
the current workfile. name_pattern is used to list the objects you wish to compare. The typi-
cal form of targetspec is simply “*”, meaning to compare all objects in the current workfile.

baselinespec should be a specification of the list of objects to compare against. It should take
the form of [container::page\]name_pattern, where the optional container::page\ may be
used to specify the name of the workfile or database or page containing the objects to com-
pare against. name_pattern is used to list the objects you wish to compare against. If base-
linespec is blank, the version of the current workfile stored on disk is used as the baseline.

The optional @keep and @drop lists allow you to narrow further the list of objects in tar-
getspec by listing specific objects to compare (using @keep), or drop from the targetspec
(using @drop).
wfcompare—633

Options
tol=arg Specifies the threshold below which differences between
the target and baseline values should be ignored. The
threshold is specified as a fraction of the baseline value. For
example, if tol=1%, one or more observations in the target
object must differ from their values in the baseline object
by at least one percent for the objects to be reported as dif-
ferent. The default tolerance is 1e-15.
seterr Set an error if any differences exceeding the specified toler-
ance were found. This option may be useful in batch pro-
gramming to alert the user if a program causes
unexpectedly large changes to data values.
list=key Selects which objects should be included in the output list.
key may be “a” (list objects that exist in the target but not
baseline), “d” (list objects that exist in the baseline, but not
target), “r” (list objects that exist in both but have different
objects types), “c” (list objects that exist in both but have
different frequencies), “m” (list objects that exist in both
but have values that differ by more than the tolerance), “u”
(list objects that exist in both and are unchanged), “s” (list
objects that exist in both but cannot be compared).
out=name Create a table object name, containing the comparison
table.
nohead Used with “out=” option to suppress the header row at the
top of the frozen table.

Examples
wfcompare

Compares the current workfile with the previously saved version of the workfile on disk. All
pages are compared.
wfcompare *_0 *_1

compares all in the current page with names ending with “_0” with all objects whose names
ends in “_1”.
wfcompare page1\* page2\*

compares all objects in page1 of the current workfile with those in page2.
wfcompare page1\* page2\* @drop GDP UNEMP

compares all objects except for the objects “GDP” and “UNEMP” in page1 of the current
workfile with those in page2.
634—Chapter 17.Command Reference

wfcompare * myfile.wf1

compares the contents of the current page with the contents of the same page in the saved
workfile 'myfile.wf1'
wfcompare *\* jun2012.wf1

compares the contents of all pages in the current workfile in memory with all pages of the
saved workfile “Jun2012.WF1”.
wfcompare page2\x* test.edb::y*

compares all objects in page2 of the current workfile whose name begins with the letter “x”
to all objects in the database test.edb whose name begins with the letter “y”.

Cross-references
See “Comparing Workfiles,” on page 81 of User’s Guide I for discussion.

wfcreate Object Container, Data, and File Commands

Create a new workfile. The workfile becomes the active workfile.

Syntax
wfcreate(options) frequency[(subperiod_opts)] start_date end_date [num_cross_sec-
tions]
wfcreate(options) frequency[(subperiod_opts)] start_date +num_observations
wfcreate(options) u num_observations

The first form of the command may be used to create a new regular frequency workfile with
the specified frequency, start, and end date. Subperiod options may also be specified for
intraweek or intraday data. See table below for a complete description for each frequency. If
you include the optional num_cross_sections, EViews will create a balanced panel page
using integer identifiers for each of the cross-sections. Note that more complex panel struc-
tures may be created using pagestruct (p. 558). You may use the @now keyword to specify
the current date/time as either the start_date or end_date.

The second form of the command may be used to create a new regular frequency workfile
with a specified frequency, start date and number of observations. The end date is calcu-
lated as the start date plus the number of periods (determined by the frequency specifica-
tion) given by num_observations.

The third form of the command is used to create an unstructured workfile with the specified
number of observations.
wfcreate—635

Options
wf=wf_name Optional name for the new workfile.
page=page_name Optional name for the page in the new workfile.
prompt Force the dialog to appear from within a program.

Arguments
The frequency argument should be specified using one of the following forms:
Sec[opt], 5Sec[opt], Seconds in intervals of: 1, 5, 15, or 30 seconds, respec-
15Sec[opt], tively. You may optionally specify days of the week and
30Sec[opt] start and end times during the day using the opt parameter.
See explanation of subperiod options below.
Min[opt], Minutes in intervals of: 1, 2, 5, 10, 15, 20, or 30 minutes,
2Min[opt], respectively. You may optionally specify days of the week
5Min[opt], and start and end times during the day using the opt
10Min[opt], parameter. See explanation of subperiod options below.
15Min[opt],
20Min[opt],
30Min[[opt]
H[opt], 2H[opt], Hours in intervals of: 1, 2, 4, 6, 8, or 12 hours, respectively.
4H[opt], 6H[opt], You may optionally specify days of the week and start and
8H[opt], 12H[[opt] end times during the day using the opt parameter. See
explanation of subperiod options below.
D(s, e) Daily with arbitrary days of the week. Specify the first and
last days of the week with integers s and e, where Monday
is given the number 1 and Sunday is given the number 7.
(Note that the “D” option used to specify a 5-day frequency
prior to EViews 7.)
D5 or 5 Daily with five days per week, Monday through Friday.
D7 or 7 Daily with seven days per week.
W Weekly
T Ten-day (daily in intervals of ten).
F Fortnight
BM Bimonthly
M Monthly
Q Quarterly
S Semi-annual
A or Y Annual
636—Chapter 17.Command Reference

2Y, 3Y, 4Y, 5Y, 6Y, Multi-year in intervals of: 2, 3, 4, 5, 6, 7, 8, 9, 10, or 20


7Y, 8Y, 9Y, 10Y, 20Y years, respectively.

Subperiod options
EViews allows for setting the days of the week and the time of day within intraday frequen-
cies, which include seconds, minutes, and hours. For instance, you may specify hourly data
between 8AM and 5PM on Monday through Wednesday. These subperiod options should
follow the frequency keyword and be enclosed in parentheses.

To specify days of the week, use integers to indicate the days, where Monday is given the
number 1 and Sunday is given the number 7. For example,
wfcreate(wf=storehours) 30MIN(1-6, 8:00-17:00) 1/3/2000 12/30/2000

indicates a half-hour frequency that includes Monday through Saturday from 8AM to 5PM.

To specify the start and end times, you may use either a 24 hour clock, including minutes
and optionally seconds, or a 12 hour clock using AM and PM. For example, each of the fol-
lowing represents 8PM: 8PM, 8:00PM, 8:00:00PM, 20:00, and 20:00:00. Thus, our previous
example could have been written:
wfcreate(wf=storehours) 30MIN(1-6, 8AM-5PM) 1/3/2000 12/30/2000

If you wish to include all days of the week but would like to specify a start and end time, set
the date range to include all days and then specify the times. The day of the week parameter
appears first and is required if you wish to supply the time of day parameters. For instance,
wfcreate(wf=storehours) 30MIN(1-7, 10AM-3PM) 1/3/2000 12/30/2000

indicates a half-hour frequency from 10AM to 3PM on all days of the week.

You may also include a time with the start and end date parameters to specify partial days at
the beginning or end of the workfile. For example,
wfcreate(wf=storehours) 30MIN(1-6, 8AM-5PM) 1/3/2000 10AM
12/30/2000 2PM

creates the same workfile as above, but limits the first day, 1/3/2000, to 10AM - 5PM and the
last day, 12/30/2000, to 8AM - 2PM.
Alignment options
Certain frequencies optionally allow you to specify the starting point of the frequency
period. Weekly and biweekly frequencies allow you to set the day at which the week begins.
Annual, semiannual and quarterly frequencies allow you to set the month at which the
quarter or year begins. Setting the starting period is important if you wish to use frequency
conversion to convert data from a different frequency.
wfcreate—637

To specify the start period, simply add an extra term to the frequency symbol, surrounded in
parenthesis, containing the day, or month, upon which you wish the frequency to start. For
example:
wfcreate w(monday) 2000 2010

creates a weekly workfile from 2000 to 2010, where each week starts on a Monday.
wfcreate a(july) 2001 2007

creates an annual workfile where each year starts in July.

Note that by default, if you do not specify a starting point, EViews will use the period of the
specified start_date. To make this difference concrete, consider the commands:
wfcreate w 2000 2010

and
wfcreate w(monday) 2000 2010

Since January 1st, 2000 was a Saturday, the first command will create a weekly workfile
where each week starts on a Saturday, and the first observation in the workfile will span the
period January 1st-January 7th 2000.

The second command will force EViews to start weeks on a Monday, and thus the first
observation will actually span the period December 27th 1999 - January 2nd 2000.

Examples
wfcreate(wf=annual, page=myproject) a 1950 2005
wfcreate(wf=unstruct, page=undated) u 1000

creates two workfiles. The first is a workfile named ANNUAL containing a single page
named MYPROJECT containing annual data from 1950 to 2005; the second is a workfile
named UNSTRUCT containing a single page named UNDATED with 1000 unstructured
observations.
wfcreate(wf=griliches_grunfeld, page=annual) a 1935 1954 10

creates the GRILICHES_GRUNFELD workfile containing a page named “ANNUAL” with 10


cross-sections of annual data for the years 1935 to 1954.
wfcreate(wf=fourday) D(1,4) 1/3/2000 12/31/2000

specifies a daily workfile from January 3, 2000 to December 31, 2000, including only Mon-
day through Thursday. The day range may be delimited by either a comma or a dash, such
that
wfcreate(wf=fourday) D(1-4) 1/3/2000 12/31/2000

is equivalent to the previous command.


wfcreate(wf=captimes) 15SEC(2-4) 1/3/2000 12/30/2000
638—Chapter 17.Command Reference

creates a workfile with 15 second intervals on Tuesday through Thursday only, from
1/3/2000 to 12/30/2000.
wfcreate m 1995 +30

will create a monthly workfile starting in January 1995 and ending in July 1997.

Cross-references
See “Creating a Workfile,” on page 30 of User’s Guide I for discussion.

See also pagecreate (p. 540) and pagedelete (p. 546).

wfdetails Object Container, Data, and File Commands

Change the details displayed in the current workfile window, optionally freezing the
results into a table object in the current workfile.

Syntax
wfdetails(options) col1[(width1)] [col2[(width2)].....] @sort sortcol

Specify the names of the attribute columns you would like to display in the workfile details
view, optionally including the width of the column in parenthesis. Widths can be specified
with positive numbers, indicating a width in pixels, or negative numbers if you wish to spec-
ify the width in approximate characters.

You may use the @sort keyword at the end of the specification to indicate by which column
to sort the details view.

Options
out=name Create a table object name, containing the details view
table.
nohead Used with “out=” option to suppress the header row at the
top of the frozen table.

Examples
wfdetails start end

shows the workfile details view, with the attribute columns “start” and “end”.
wfdetails(out=dettable) start(30) end(-10)

shows the same view, but setting the “start” column’s width to 30 pixels, and the “end” col-
umn’s width to 10 characters, and freezing the view into a table called DETTABLE.
wfdetails start end @sortcol type
wffilter—639

sorts the details view by object type.

Cross-references
See “Workfile Details Display,” on page 51 of User’s Guide I for discussion.

wfdir Object Container, Data, and File Commands

Change the workfile view to a simple object directory listing.

Syntax
wfdir

If the workfile is currently in details view, the wfdir command switches the view back to a
simple directory listing.

Cross-references
See “Workfile Details Display,” on page 51 of User’s Guide I for discussion.

wffilter Object Container, Data, and File Commands

Change the workfile object filter for the current workfile window.

Syntax
wffilter name_list @ object_type_list @attr(attribute_list)

Specify the names of the objects you would like to display in the workfile window using a
name pattern. You may additionally specify the object type(s) using the @ delimiter and/or
matching attribute value using the @attr keyword.
• The name_list is a space delimited list of names or name patterns.
• The object_type_list is a space delimited list of one or more object types or object
groups. The start of the list is denoted by the '@' symbol followed by a space.
• The attribute_list is a space delimited list of attribute filters. Each applied filter is
denoted by using the @attr keyword. The format of the filter has the form
@attr(attr_name, attr_value).

Acceptable individual object types include:


series, group, alpha, link, sample, valmap, table, graph, text, spool, equation, var, sys-
tem, logl, pool, factor, sspace, vector, sym, matrix, coef, scalar, model, user
Individual object types are also categorized into object groups:
640—Chapter 17.Command Reference

Options
estobj equation, var, system, logl, pool, factor, sspace
matobj vector, sym, matrix, coef, scalar
viewobj table, graph, text, spool
dataobj series, group, alpha, link, sample, valmap

Examples
wffilter tab1 graph1

displays the objects tab1 and graph1 in the workfile window if they exist.
wffilter a* t*

displays in the workfile window all objects whose names begin with “a” or “t”.
wffilter * @ series

displays all the series objects in the workfile window.


wffilter g* @ series graph

displays in the workfile window the series and graph objects beginning with “g”.
wffilter * @attr("remarks","us gdp")”

displays in the workfile window the objects in the workfile whose remarks attributes are ‘us
gdp”.
wffilter p* @ matobj @attr("city","") @attr("country","*US*")

displays in the workfile window the objects whose names start with “p”, are either vectors,
syms, matrices, coefs, or scalars, have an empty ‘city’ attribute, and have the string ‘us’ in
the ‘country’ attribute.

Cross-references
See “Filtering the Workfile Display,” on page 62 of User’s Guide I for discussion.

wfopen Object Container, Data, and File Commands

Open a workfile. Reads in a previously saved workfile from disk, or reads the contents of a
foreign data source into a new workfile.

The opened workfile becomes the default workfile; existing workfiles in memory remain on
the desktop but become inactive.
wfopen—641

Syntax
wfopen [path\]source_name
wfopen(options) source_description [table_description] [variables_description]
wfopen(options) source_description [table_description] [dataset_modifiers]

where path is an optional local path or URL.

There are three basic forms of the wfopen command:


• the first form is used by EViews native (“EViews and MicroTSP” on page 643) and
time series database formats (“Time Series Formats” on page 644).
• the second form used for raw data files—Excel, Lotus, ASCII text, and binary files
(“Raw Data Formats” on page 644).
• the third form is used with the remaining source formats, which we term dataset for-
mats, since the data have already been arranged in named variables (“Datasets” on
page 653).

(See “Options” on page 642 for a description of the supported source formats and corre-
sponding types.)

In all three cases, the workfile or external data source should be specified as the first argu-
ment following the command keyword and options.
• In most cases, the external data source is a file, so the source_description will be the
description of the file (including local path or URL information, if necessary). Alterna-
tively, the external data source may be the output from a web server, in which case
the URL should be provided. Similarly, when reading from an ODBC query, the ODBC
DSN (data source name) should be used as the source_description.
If the source_description contains spaces, it must be enclosed in (double) quotes.

For raw and dataset formats, you may use table_description to provide additional informa-
tion about the data to be read:
• Where there is more than one table that could be formed from the specified external
data source, a table_description may be provided to select the desired table. For exam-
ple, when reading from an Excel file, an optional cell range may be provided to specify
which data are to be read from the spreadsheet. When reading from an ODBC data
source, a SQL query or table name must be used to specify the table of data to be
read.
• In raw data formats, the table_description allows you to provide additional informa-
tion regarding names and descriptions for variables to be read, missing values codes,
settings for automatic format, and data range subsetting.
642—Chapter 17.Command Reference

• When working with text or binary files, the table_description must be used to describe
how to break up the file into columns and rows.

For raw and non-EViews dataset formats, you may use the dataset_modifiers specification to
select the set of variables, maps (value labels), and observations to be read from the source
data. The dataset_modifiers consists of the following keyword delimited lists:
[@keep keep_list] [@drop drop_list] [@keepmap keepmap_list] [@dropmap
dropmap_list] [@selectif condition]
• The @keep and @drop keywords, followed by a list of names and patterns, are used to
specify variables to be retain or dropped. Similarly, the @keepmap and @dropmap
keywords followed by lists of name patterns controls the reading of value labels. The
keyword @selectif, followed by an if condition (e.g., “if age>30 and gender=1”)
may be used to select a subset of the observations in the original data. By default, all
variables, value labels, and observations are read.

By default, all variables, maps and observations in the source file will be read.

Options
type=arg, t=arg Optional type specification: (see table below).
ODBC support is not provided in EViews Standard Edition.
link Link the object to the source data so that the values can be
refreshed at a later time.
wf=wf_name Optional name for the new workfile.
page=page_name Optional name for the page in the new workfile.
prompt Force the dialog to appear from within a program.

For the most part, you should not need to specify a “type=” option as EViews will automat-
ically determine the type from the filename.

The following table summaries the various source formats and types, along with the corre-
sponding “type=” keywords:

Source Type Option Keywords


Access dataset “access”
Aremos-TSD time series database “a”, “aremos”, “tsd”
Binary raw data “binary”
dBASE dataset “dbase”
Excel (through 2003) raw data “excel”
Excel 2007 (xml) raw data “excelxml”
EViews Workfile native ---
wfopen—643

Gauss Dataset dataset “gauss”


GiveWin/PcGive time series database “g”, “give”
HTML raw data “html”
Lotus 1-2-3 raw data “lotus”
ODBC Dsn File dataset “dsn”
ODBC Query File dataset “msquery”
ODBC Data Source dataset “odbc”
MicroTSP Workfile native “dos”, “microtsp”
MicroTSP Mac Workfile native “mac”
RATS 4.x time series database “r”, “rats”
RATS Portable / TROLL time series database “l”, “trl”
SAS Program dataset “sasprog”
SAS Transport dataset “sasxport”
SPSS dataset “spss”
SPSS Portable dataset “spssport”
Stata dataset “stata”
Text / ASCII raw data “text”
TSP Portable time series database “t”, “tsp”

EViews and MicroTSP


The syntax for EViews and MicroTSP files is:
wfopen [path\]workfile_name

where path is an option local path or URL.

Examples
wfopen c:\data\macro

loads a previously saved EViews workfile “Macro.WF1” from the “data” directory in the C
drive.
wfopen c:\tsp\nipa.wf

loads a MicroTSP workfile “Nipa.WF”. If you do not use the workfile type option, you
should add the extension “.WF” to the workfile name when loading a DOS MicroTSP work-
file. An alternative method specifies the type explicitly:
wfopen(type=dos) nipa

The command:
wfopen "<mydropboxdrive>\folder\nipa.wf1"
644—Chapter 17.Command Reference

will open the file from the cloud location MYDROPBOXDRIVE.


Time Series Formats
The syntax for time series format files (Aremos-TSD, GiveWin/PcGive, RATS, RATS Porta-
ble/TROLL, TSP Portable) is:
wfopen(options) [path\]source_name

where path is an optional local path or URL.

If the source files contain data of multiple frequencies, the resulting workfile will be of the
lowest frequency, and higher frequency data will be converted to this frequency. If you wish
to obtain greater control over the workfile creation, import, or frequency conversion pro-
cesses, we recommend that you open the file using dbopen (p. 428) and use the database
tools to create your workfile.

Aremos Example
wfopen dlcs.tsd
wfopen(type=aremos) dlcs.tsd

open the AREMOS-TSD file DLCS.

GiveWin/PcGive Example
wfopen "f:\project\pc give\data\macrodata.in7"
wfopen(type=give) "f:\project\pc give\data\macrodata"

open the PcGive file MACRODATA.

Rats Examples
wfopen macrodata.rat"
wfopen macrodata.trl

read the native RATS 4.x file MACRODATA.RAT and the RATS Portable/TROLL file
“Macrodata.TRL”.

TSP Portable Example


wfopen macrodata.tsp

reads the TSP portable file “Macrodata.TSP”.

Raw Data Formats


The command for reading raw data (Excel 97-2003, Excel 2007, HTML, ASCII text, Binary,
Lotus 1-2-3) is
wfopen(options) source_description [table_description] [variables_description]
[@keep keep_list] [@drop drop_list] [@keepmap keepmap_list] [@dropmap
dropmap_list] [@selectif condition]
wfopen—645

where the syntax of the table_description and variables_description differs slightly depend-
ing on the type of file.

Excel and Lotus Files


The syntax for reading Excel and Lotus files is:
wfopen(options) source_description [table_description] [variables_description]

The following table_description elements may be used when reading Excel and Lotus data:
• “range = arg”, where arg is a range of cells to read from the Excel workbook, follow-
ing the standard Excel format [worksheet!][topleft_cell[:bottomright_cell]].
If the worksheet name contains spaces, it should be placed in single quotes. If the
worksheet name is omitted, the cell range is assumed to refer to the currently active
sheet. If only a top left cell is provided, a bottom right cell will be chosen automati-
cally to cover the range of non-empty cells adjacent to the specified top left cell. If
only a sheet name is provided, the first set of non-empty cells in the top left corner of
the chosen worksheet will be selected automatically. As an alternative to specifying
an explicit range, a name which has been defined inside the excel workbook to refer
to a range or cell may be used to specify the cells to read.
• “byrow”, transpose the incoming data. This option allows you to read files where the
series are contained in rows (one row per series) rather than columns.

The optional variables_description may be formed using the elements:


• “colhead=int”, number of table rows to be treated as column headers.
• “namepos = [first|firstatt|last|lastatt|all|none|attonly|discard|custom]”, which row(s)
of the column headers should be used to form the column name, and also how to use
the rest. The setting “first” (or “last”) refers to the object name being in the first (or
last) column header row, and all other rows as the object's description. Similarly,
“firstatt” (or “lastatt”) will use the first (or last) row as the name field, but will use all
others as a custom attribute. The setting “all” will concatenate all column header
fields into the object's name. “none” will concatenate all column header fields into
the object's description. “attonly” will save all column header fields into the object's
custom attributes. “discard” will skip all header rows altogether, and “custom” will
allow you to specify explicitly how to treat each column header row using the
“colheadnames=” argument. The default setting is “all” if no “colheadnames=” is
specified, otherwise “custom”.
• "colheadnames = ("arg1", "arg2")", required when “namepos=custom”. Specifies
the name & type of each column header row. “Name” will be mapped to the object
name, “Description” to the object's description field, and the rest will be stored as
custom object attributes. Any blank name will cause that column header row to be
skipped.
646—Chapter 17.Command Reference

• “nonames”, the file does not contain a column header (same as “colhead=0”).
• “names=("arg1","arg2",…)”, user specified column names, where arg1, arg2, … are
names of the first series, the second series, etc. when names are provided, these over-
ride any names that would otherwise be formed from the column headers.
• “descriptions=("arg1","arg2",…)”, user specified descriptions of the series. If
descriptions are provided, these override any descriptions that would otherwise be
read from the data.
• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w” (EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
• “scan=[int| all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a “range=” argument is not specified,
then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the “na=” argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the “scan=” argument to instruct EViews to look at more rows. In addition, you may
want to specify a the “na=” value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the table of data (default is 1).
This option may be used to start reading rows from partway through the table.
• “lastobs=int”, last observation to be read from the table of data (default is last obser-
vation of the file). This option may be used to read only part of the file, which may be
useful for testing.

Excel Examples
wfopen "c:\data files\data.xls"

loads the active sheet of DATA.XLS into a new workfile.


wfopen(page=mypage) "c:\data files\data.xls" range="GDP data"
@drop X

reads the data contained in the “GDP data” sheet of “Data.XLS” into the MYPAGE page of a
new workfile. The data for the series X is dropped, and the name of the new workfile page is
“GDP”.
wfopen—647

To load the Excel file containing US Macro Quarterly data from Stock and Watson’s Introduc-
tion to Econometrics you may use the command:
wfopen
http//wps.aw.com/wps/media/objects/3254/3332253/datasets2e/dat
asets/USMacro_Quarterly.xls

which will load the Excel file directly into EViews from the publisher’s website (as of
08/2009).

HTML Files
The syntax for reading HTML pages is:
wfopen(options) source_description [table_description] [variables_description]

The following table_description elements may be used when reading an HTML file or page:
• “table = arg”, where arg specifies which table to read in an HTML file/page contain-
ing multiple tables.
When specifying arg, you should remember that tables are named automatically fol-
lowing the pattern “Table01”, “Table02”, “Table03”, etc. If no table name is specified,
the largest table found in the file will be chosen by default. Note that the table num-
bering may include trivial tables that are part of the HTML content of the file, but
would not normally be considered as data tables by a person viewing the page.
• “skip = int”, where int is the number of rows to discard from the top of the HTML
table.
• “byrow”, transpose the incoming data. This option allows you to import files where
the series are contained in rows (one row per series) rather than columns.

The optional variables_description may be formed using the elements:


• “colhead=int”, number of table rows to be treated as column headers.
• “namepos = [first|firstatt|last|lastatt|all|none|attonly|discard|custom]”, which row(s)
of the column headers should be used to form the column name, and also how to use
the rest. The setting “first” (or “last”) refers to the object name being in the first (or
last) column header row, and all other rows as the object's description. Similarly,
“firstatt” (or “lastatt”) will use the first (or last) row as the name field, but will use all
others as a custom attribute. The setting “all” will concatenate all column header
fields into the object's name. “none” will concatenate all column header fields into
the object's description. “attonly” will save all column header fields into the object's
custom attributes. “discard” will skip all header rows altogether, and “custom” will
allow you to specify explicitly how to treat each column header row using the
“colheadnames=” argument. The default setting is “all” if no “colheadnames=” is
specified, otherwise “custom”.
648—Chapter 17.Command Reference

• "colheadnames = ("arg1", "arg2")", required when “namepos=custom”. Specifies


the name & type of each column header row. “Name” will be mapped to the object
name, “Description” to the object's description field, and the rest will be stored as
custom object attributes. Any blank name will cause that column header row to be
skipped.
• “nonames”, the file does not contain a column header (same as “colhead=0”).
• “names=("arg1","arg2",…)”, user specified column names, where arg1, arg2, … are
names of the first series, the second series, etc. when names are provided, these over-
ride any names that would otherwise be formed from the column headers.
• “descriptions=("arg1","arg2",…)”, user specified descriptions of the series. If
descriptions are provided, these override any descriptions that would otherwise be
read from the data.
• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w”(EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
• “scan=[int|all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a "range=" argument is not specified,
then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the "na=" argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the "scan=" argument to instruct EViews to look at more rows. In addition, you may
want to specify a the "na=" value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the table of data (default is 1).
This option may be used to start reading rows from partway through the table.
• “lastobs = int”, last observation to be read from the table of data (default is last
observation of the file). This option may be used to read only part of the file, which
may be useful for testing.

HTML Examples
wfopen "c:\data.html"

loads into a new workfile the data located on the HTML file “Data.HTML” located on the C:\
drive
wfopen—649

wfopen(type=html)
"http://www.tradingroom.com.au/apps/mkt/forex.ac" colhead=3,
namepos=first

loads into a new workfile the data with the given URL located on the website site
“http://www.tradingroom.com.au”. The column header is set to three rows, with the first
row used as names for columns, and the remaining two lines used to form the descriptions.

Text and Binary Files


The syntax for reading text or binary files is:
wfopen(options) source_description [table_description] [variables_description]

If a table_description is not provided, EViews will attempt to read the file as a free-format
text file. The following table_description elements may be used when reading a text or
binary file:
• “ftype = [ascii|binary]” specifies whether numbers and dates in the file are stored in
a human readable text (ASCII), or machine readable (Binary) form.
• “rectype = [crlf|fixed|streamed]” describes the record structure of the file:
“crlf”, each row in the output table is formed using a fixed number of lines from
the file (where lines are separated by carriage return/line feed sequences). This is
the default setting.
“fixed”, each row in the output table is formed using a fixed number of charac-
ters from the file (specified in “reclen= arg”). This setting is typically used for
files that contain no line breaks.
“streamed”, each row in the output table is formed by reading a fixed number of
fields, skipping across lines if necessary. This option is typically used for files that
contain line breaks, but where the line breaks are not relevant to how rows from
the data should be formed.
• “reclines =int”, number of lines to use in forming each row when “rectype=crlf”
(default is 1).
• “reclen=int”, number of bytes to use in forming each row when “rectype=fixed”.
• “recfields=int”, number of fields to use in forming each row when “rec-
type=streamed”.
• “skip=int”, number of lines (if rectype is “crlf”) or bytes (if rectype is not “crlf”) to
discard from the top of the file.
• “comment=string“, where string is a double-quoted string, specifies one or more
characters to treat as a comment indicator. When a comment indicator is found,
everything on the line to the right of where the comment indicator starts is ignored.
650—Chapter 17.Command Reference

• “emptylines=[keep|drop]”, specifies whether empty lines should be ignored


(“drop”), or treated as valid lines (“keep”) containing missing values. The default is
to ignore empty lines.
• “tabwidth=int”, specifies the number of characters between tab stops when tabs are
being replaced by spaces (default=8). Note that tabs are automatically replaced by
spaces whenever they are not being treated as a field delimiter.
• “fieldtype=[delim|fixed|streamed|undivided]”, specifies the structure of fields within
a record:
“Delim”, fields are separated by one or more delimiter characters
“Fixed”, each field is a fixed number of characters
“Streamed”, fields are read from left to right, with each field starting immediately
after the previous field ends.
“Undivided”, read entire record as a single series.
• “quotes=[single|double|both|none]”, specifies the character used for quoting fields,
where “single” is the apostrophe, “double” is the double quote character, and “both”
means that either single or double quotes are allowed (default is “both”). Characters
contained within quotes are never treated as delimiters.
• “singlequote“, same as “quotes = single”.
• “delim=[comma|tab|space|dblspace|white|dblwhite]”, specifies the character(s) to
treat as a delimiter. “White” means that either a tab or a space is a valid delimiter. You
may also use the abbreviation “d=” in place of “delim=”.
• “custom="arg1"”, specifies custom delimiter characters in the double quoted string.
Use the character “t” for tab, “s” for space and “a” for any character.
• “mult=[on|off]”, to treat multiple delimiters as one. Default value is “on” if “delim”
is “space”, “dblspace”, “white”, or “dblwhite”, and “off” otherwise.
• “endian = [big|little]”, selects the endianness of numeric fields contained in binary
files.
• “string = [nullterm|nullpad|spacepad]”, specifies how strings are stored in binary
files. If “nullterm”, strings shorter than the field width are terminated with a single
zero character. If “nullpad”, strings shorter than the field width are followed by extra
zero characters up to the field width. If “spacepad”, strings shorter than the field
width are followed by extra space characters up to the field width.
• “byrow”, transpose the incoming data. This option allows you to import files where
the series are contained in rows (one row per series) rather than columns.
• “lastcol”, include implied last column. For lines that end with a delimiter, this option
adds an additional column. When importing a CSV file, lines which have the delimiter
wfopen—651

as the last character (for example: “name, description, date”), EViews normally deter-
mines the line to have 3 columns. With the above option, EViews will determine the
line to have 4 columns. Note this is not the same as a line containing “name, descrip-
tion, date”. In this case, EViews will always determine the line to have 3 columns
regardless if the option is set.

A central component of the table_description element is the format statement. You may
specify the data format using the following table descriptors:
• Fortran Format:
fformat=([n1]Type[Width][.Precision], [n2]Type[Width][.Precision], ...)
where Type specifies the underlying data type, and may be one of the following,
I - integer
F - fixed precision
E - scientific
A - alphanumeric
X - skip
and n1, n2, ... are the number of times to read using the descriptor (default=1). More
complicated Fortran compatible variations on this format are possible.
• Column Range Format:
rformat="[n1]Type[Width][.Precision], [n2]Type[Width][.Precision], ...)"
where optional type is “$” for string or “#” for number, and n1, n2, n3, n4, etc. are the
range of columns containing the data.
• C printf/scanf Format:
cformat="fmt"
where fmt follows standard C language (printf/scanf) format rules.

The optional variables_description may be formed using the elements:


• “colhead=int”, number of table rows to be treated as column headers.
• “namepos = [first|firstatt|last|lastatt|all|none|attonly|discard|custom]”, which row(s)
of the column headers should be used to form the column name, and also how to use
the rest. The setting “first” (or “last”) refers to the object name being in the first (or
last) column header row, and all other rows as the object's description. Similarly,
“firstatt” (or “lastatt”) will use the first (or last) row as the name field, but will use all
others as a custom attribute. The setting “all” will concatenate all column header
fields into the object's name. “none” will concatenate all column header fields into
the object's description. “attonly” will save all column header fields into the object's
custom attributes. “discard” will skip all header rows altogether, and “custom” will
allow you to specify explicitly how to treat each column header row using the
652—Chapter 17.Command Reference

“colheadnames=” argument. The default setting is “all” if no “colheadnames=” is


specified, otherwise “custom”.
• "colheadnames = ("arg1", "arg2")", required when “namepos=custom”. Specifies
the name & type of each column header row. “Name” will be mapped to the object
name, “Description” to the object's description field, and the rest will be stored as
custom object attributes. Any blank name will cause that column header row to be
skipped.
• “nonames”, the file does not contain a column header (same as “colhead=0”).
• “names=("arg1", "arg2",…)”, user specified column names, where arg1, arg2, … are
names of the first series, the second series, etc. when names are provided, these over-
ride any names that would otherwise be formed from the column headers.
• “descriptions=("arg1", "arg2",…)”, user specified descriptions of the series. If
descriptions are provided, these override any descriptions that would otherwise be
read from the data.
• “types=("arg1","arg2",…)”, user specified data types of the series. If types are pro-
vided they will override the types automatically detected by EViews. You may use any
of the following format keywords: “a” (character data), “f” (numeric data), “d”
(dates), or “w” (EViews automatic detection). Note that the types appear without
quotes: e.g., “types=(a,a,a)”.
• “na="arg1"”, text used to represent observations that are missing from the file. The
text should be enclosed on double quotes.
• “scan=[int|all]”, number of rows of the table to scan during automatic format detec-
tion (“scan=all” scans the entire file). Note: If a “range=” argument is not specified,
then EViews will only scan the first five rows of data to try and determine the data for-
mat for each column. Likewise, if the “na=” argument is not specified, EViews will
also try to determine possible NA values by looking for repeated values in the same
rows. If the first five rows are not enough to correctly determine the data format, use
the “scan=” argument to instruct EViews to look at more rows. In addition, you may
want to specify a the “na=” value to override any dynamic NA value that EViews may
determine on its own.
• “firstobs=int”, first observation to be imported from the table of data (default is 1).
This option may be used to start reading rows from partway through the table.
• “lastobs = int”, last observation to be read from the table of data (default is last
observation of the file). This option may be used to read only part of the file, which
may be useful for testing.

Text and Binary File Examples (.txt, .csv, etc.)


wfopen c:\data.csv skip=5, names=(gdp, inv, cons)
wfopen—653

reads “Data.CSV” into a new workfile page, skipping the first 5 rows and naming the series
GDP, INV, and CONS.
wfopen(type=text) c:\date.txt delim=comma

loads the comma delimited data DATE.TXT into a new workfile.


wfopen(type=raw) c:\data.txt skip=8, rectype=fixed,
format=(F10,X23,A4)

loads a text file with fixed length data into a new workfile, skipping the first 8 rows. The
reading is done as follows: read the first 10 characters as a fixed precision number, after that,
skip the next 23 characters (X23), and then read the next 4 characters as strings (A4).
wfopen(type=raw) c:\data.txt rectype=fixed, format=2(4F8,2I2)

loads the text file as a workfile using the specified explicit format. The data will be a repeat
of four fixed precision numbers of length 8 and two integers of length 2. This is the same
description as “format=(F8,F8,F8,F8,I2,I2,F8,F8,F8,F8,I2,I2)”.
wfopen(type=raw) c:\data.txt rectype=fixed, rformat="GDP 1-2 INV 3
CONS 6-9"

loads the text file as a workfile using column range syntax. The reading is done as follows:
the first series is located at the first and second character of each row, the second series
occupies the 3rd character, the third series is located at character 6 through 9. The series will
named GDP, INV, and CONS.

Datasets
The syntax for reading data from the remaining sources (Access, Gauss, ODBC, SAS pro-
gram, SAS transport, SPSS, SPSS portable, Stata) is:
wfopen(options) source_description table_description [@keep keep_list] [@drop
drop_list] [@selectif condition]

Note that for this purpose we view Access and ODBC as datasets.

ODBC or Microsoft Access


The syntax for reading from an ODBC or Microsoft Access data source is
wfopen(options) source_description table_description [@keep keep_list] [@drop
drop_list] [@selectif condition]

When reading from an ODBC or Microsoft Access data source, you must provide a table_de-
scription to indicate the table of data to be read. You may provide this information in one of
two ways: by entering the name of a table in the data source, or by including an SQL query
statement enclosed in double quotes.

ODBC support is not provided in EViews Standard Edition.


654—Chapter 17.Command Reference

ODBC Examples
wfopen c:\data.dsn CustomerTable

opens in a new workfile the table named CUSTOMERTABLE from the ODBC database
described in the DATA.DSN file.
wfopen(type=odbc) "my server" "select * from customers where id>30"
@keep p*

opens in a new workfile with SQL query from database using the server “MY SERVER”,
keeping only variables that begin with P. The query selects all variables from the table CUS-
TOMERS where the ID variable takes a value greater than 30.

Other Dataset Types


The syntax for reading data from the remaining sources (Gauss, SAS program, SAS trans-
port, SPSS, SPSS portable, Stata) is:
wfopen(options) source_description [@keep keep_list] [@drop drop_list] [@selectif
condition]

Note that no table_description is required.

SAS Program Example


If a data file, “Sales.DAT”, contains the following space delimited data:
AZ 110 1002
CA 200 2003
NM 90 908
OR 120 708
WA 113 1123
UT 98 987

then the following SAS program file can be read by EViews to open the data:
Data sales;
infile sales.dat';
input state $ price sales;
run;

SAS Transport Examples


wfopen(type=sasxport) c:\data.xpt

loads a SAS transport file “data.XPT” into a new workfile.


wfopen c:\inst.sas
wforder—655

creates a workfile by reading from external data using the SAS program statements in
“Inst.SAS”. The program may contain a limited set of SAS statements which are commonly
used in reading in a data file.

Stata Examples
To load a Stata file “Data.DTA” into a new workfile, dropping maps MAP1 and MAP2, you
may enter:
wfopen c:\data.dta @dropmap map1 map2

To download the sports cards dataset from Stock and Watson’s Introduction to Econometrics
you may use the command:
wfopen
http://wps.aw.com/wps/media/objects/3254/3332253/datasets2e/da
tasets/Sportscards.dta

which will load the Stata dataset directly into EViews from the publisher’s website (as of
08/2009).

Cross-references
See Chapter 2. “Workfile Basics,” on page 29 of User’s Guide I for a discussion of workfiles.

See also pageload (p. 546), read (p. 570), fetch (p. 449), wfsave (p. 656), wfclose
(p. 631) and pagesave (p. 548).

wforder Object Container, Data, and File Commands

Change the workfile page order.

Syntax
wforder pagenames

where pagenames is a space delimited list of page names. If the workfile contains more
pages not listed in pagenames, they will be placed at the end.

Examples
wforder annual monthly

sets the ANNUAL page as the first page in the workfile and the MONTHLY page as the sec-
ond.
656—Chapter 17.Command Reference

wfrefresh Object Container, Data, and File Commands

Refresh all links and auto-series in the active workfile. Primarily used to refresh links that
use external database data.

Syntax
wfrefresh

Examples
wfrefresh

Cross-references
See also Chapter 8. “Series Links,” on page 249 of User’s Guide I for a description of link
objects, and “Auto-Updating Series” on page 219 of User’s Guide I for a discussion of auto-
updating series.

See also pagerefresh (p. 547), Link::link (p. 530) and Link::linkto (p. 530) in the
Object Reference.

wfsave Object Container, Data, and File Commands

Save the default workfile as an EViews workfile (.wf1 file) or as a foreign file or data
source.

Syntax
wfsave(options) [path\]filename
wfsave(options) source_description [nonames] [@keep keep_list] [@drop drop_list]
[@keepmap keepmap_list] [@dropmap dropmap_list] [@smpl smpl_spec]
wfsave(options) source_description table_description [nonames] [@keep keep_list]
[@drop drop_list] [@keepmap keepmap_list] [@dropmap dropmap_list]
[@smpl smpl_spec]

saves the active workfile in the specified directory using filename. By default, the workfile is
saved as an EViews workfile, but options may be used to save all or part of the active page in
a foreign file or data source.

When saving to a foreign data file, the basic specification consists of a “type=” option and
source_description and table_description arguments which specify the format of the foreign
data file. See below for details on source_description and table_description.

The remaining optional elements specify the actual elements to be saved.


wfsave—657

Options
Workfile (WF1) Save Options
1 Save using single precision.
2 Save using double precision.
c Save compressed workfile (not compatible with EViews
versions prior to 5.0).

Workfile (WF2) Save Options


jf Save JSON with formatting making it easier to read.
Increases file size.
nojf Saves JSON without any formatting. Minimizes file size.
gzip Saves JSON as a compressed gzip file. Minimizes file size.
nogzip Saves JSON without any gzip compression (i.e., simple text
file). Increases file size.

The default workfile save settings use the global options.


Foreign Source Save Options
These options only apply when saving your file to a format other than an EViews workfile.
note that some of the options only apply to specific file types.
type=arg, t=arg Optional type specification: (see table below).
ODBC support is not provided in EViews Standard Edition.
maptype=arg Write selected maps as: numeric (“n”), character (“c”),
both numeric and character (“b”).
nomapval Do not write mapped values for series with attached value
labels (the default is to write the mapped values if avail-
able).
noid Do not write observation identifiers to foreign data files (by
default, EViews will include a column with the date or
observation identifier).
658—Chapter 17.Command Reference

nonames Do not write variable names (only application to file for-


mats that support writing raw data without variable
names). Only available in EViews 12 and later. EViews 11
and older should use nonames as an argument after the
output file name.
na=arg String value to be used for NAs.
attr Include object attributes (if the output type supports it).
When specified, the first column will contain attribute
names and each attribute value will be displayed after the
name row.

Excel Save Options


mode=arg Specify whether to create a new file, overwrite an existing
file, or update an existing file. arg may be “create” (create
new file only; error on attempt to overwrite) or “update”
(update an existing file, only overwriting the area specified
by the range= table_description).
If the “mode=” option is not used, EViews will create a
new file, unless the file already exists in which case it will
overwrite it.
Note that the “mode=update” option is only available for
Excel in 1) Excel versions through 2003, if Excel is
installed, and 2) Excel 2007 (xml). Note: Excel does not
need to be installed for Excel 2007 writing.
wfsave—659

Excel 2007 Save Options


mode=arg Specify whether to create a new file, overwrite an existing
file, or update an existing file. arg may be “create” (create
new file only; error on attempt to overwrite) or “update”
(update an existing file, only overwriting the area specified
by the range= table_description).
If the “mode=” option is not used, EViews will create a
new file, unless the file already exists in which case it will
overwrite it.
Note that the “mode=update” option is only available for
Excel in 1) Excel versions through 2003, if Excel is
installed, and 2) Excel 2007 (xml). Note: Excel does not
need to be installed for Excel 2007 writing.
cellfmt=arg Specify whether to use EViews, pre-existing, or remove cell
formatting (colors, font, number formatting when possible,
column widths and row heights) for the written range.
arg may be “eviews” (replace current formatting in the file
with the same cell formatting in EViews), “preserve” (leave
current cell formatting already in the Excel file), or “clear”
(remove current formatting and do not replace).
strlen=arg Specify the maximum the number of characters written for
(default = 256) cells containing text. Strings in cells which are longer the
max, will be truncated.

The following table summaries the various formats along with the corresponding “type=”
keywords:

Type Keywords Supports Attributes


Access “access”
Aremos-TSD “a”, “aremos”, “tsd”
Binary “binary”
dBASE “dbase”
Excel (through 2003) “excel” Yes
Excel 2007 (xml) “excelxml” Yes
EViews Workfile ---
Gauss Dataset “gauss”
GiveWin/PcGive “g”, “give”
JSON “json”
JSON (legacy output gener- “jsonlegacy”
ated by EViews prior to
EViews 12)
660—Chapter 17.Command Reference

EViews workfile (WF1) “wf1”


EViews workfile (WF2) “wf2”
Lotus 1-2-3 “lotus”
ODBC Dsn File “dsn”
ODBC Data Source “odbc”
MicroTSP Workfile “dos”, “microtsp”
MicroTSP Mac Workfile “mac”
RATS 4.x “r”, “rats”
RATS Portable / TROLL “l”, “trl”
SAS Program “sasprog”
SAS Transport “sasxport”
SPSS “spss”
SPSS Portable “spssport”
Stata (Version 7 Format) “stata”
Tableau Data Extract tde
Text / ASCII “text” Yes
TSP Portable “t”, “tsp”

Note that if you wish to save your Excel 2007 XML file with macros enabled, you should
specify the explicit filename extension “.XLSM”.
Foreign Data Descriptions
When saving to a foreign data format the base specification consists of a basic specification
of source_description and table_description which specify the exact details of the format.

The command for saving as foreign data formats is


wfsave(options) source_description [table_description] [@keep keep_list] [@drop
drop_list] [@keepmap keepmap_list] [@dropmap dropmap_list] [@smpl
smpl_spec]

where the syntax of the table_description and variables_description differs slightly depend-
ing on the type of file.
• @keep, @drop, @keepmap, @dropmap, and @smpl arguments may be used to con-
trol what objects and observations to write.
• The nonames keyword may be used to suppress the writing of variable names in file
formats that support writing raw data without variable names.
• Note that saving as a foreign data file, with the exception of JSON, will save the cur-
rent workfile page only.
wfsave—661

• The JSON type will save all series objects from all pages of the current working, ignor-
ing any @keep, @drop, and @smpl arguments.

Excel Files
The base syntax for writing Excel files is:
wfsave(options) source_description [table_description]

where source_description is the path and name of the Excel file to be saved, and where the
following table_description elements may be employed:
• “range = arg”, where arg is a range of cells to read from the Excel workbook, follow-
ing the standard Excel format [worksheet!][topleft_cell[:bottomright_cell]].
If the worksheet name contains spaces, it should be placed in single quotes. If the
worksheet name is omitted, the cell range is assumed to refer to the currently active
sheet. If only a top left cell is provided, a bottom right cell will be chosen automati-
cally to cover the range of non-empty cells adjacent to the specified top left cell. If
only a sheet name is provided, the first set of non-empty cells in the top left corner of
the chosen worksheet will be selected automatically. As an alternative to specifying
an explicit range, a name which has been defined inside the excel workbook to refer
to a range or cell may be used to specify the cells to read.
• “byrow”, transpose the incoming data. This option allows you to read files where the
series are contained in rows (one row per series) rather than columns.

Examples
Text and Binary and Other Files
The base syntax for saving other files is:
wfsave(options) source_description

where source_description is the path and name of the file to be saved.

Examples
EViews Workfile Examples
wfsave new_wf

saves the current EViews workfile as “New_wf.WF1” in the default directory.


wfsave "c:\documents and settings\my data\consump"

saves the current workfile as “Consump.WF1” in the specified path.


wfsave macro @keep gdp unemp

saves the two series GDP and UNEMP in a separate workfile, “macro.WF1” in the default
directory.
wfsave macro @dropmap gdp*
662—Chapter 17.Command Reference

saves all of the series in the current workfile, other than those that match the name pattern
“gdp*” in a workfile, “macro.WF1” in the default directory.

The command:
wfsave "<mydropboxdrive>"\folder\nipa.wf1"

will save the file to the cloud location MYDROPBOXDRIVE.


Foreign Data Examples
wfsave(type=excelxml, mode=update) macro.xlsx

saves the current workfile page as a modern Excel “.XLSX” file.


wfsave(type=excelxml, mode=update) macro.xlsx range="Sheet2!a1"
byrow @keep gdp unemp

will save the two series GDP and UNEMP into the existing Excel file “macro.XLSX”, specify-
ing that the series should be written by row, starting in cell A1 on sheet Sheet2.

To save the latter file in a macro-enabled Excel 2007 file, you should specify the explicit file-
name extension “.XLSM”,
wfsave(type=excelxml, mode=update) macro.xlsm range="Sheet2!a1"
byrow @keep gdp unemp

Alternately,
wfsave(type=excelxml, noid) macro.xlsx range="Sheet2!a1"

will save the current workfile page as the Excel file “macro.XLSX” but will not include a col-
umn of dates.

If you wish to save a column of dates in a specific date format, you can do so by first creat-
ing an alpha series in the workfile with the specified format, then saving the file with the
“noid” option including that alpha series:
alpha mydates = @datestr(@date, "YYYY-MM-DD")
wfsave(type=excelxml, noid) macro.xlsm range="Sheet2!a1" @keep
mydates gdp unemp

will save the series GDP and UNEMP into the Excel file “macro.XLSM” along with a date
series with the format “YYYY-MM-DD”.

Cross-references
See Chapter 2. “Workfile Basics,” on page 29 of User’s Guide I for a discussion of workfiles.

See also pagesave (p. 548), wfopen (p. 640), and pageload (p. 546).
wfsnapshot—663

wfselect Object Container, Data, and File Commands

Make the selected workfile page the active workfile page.

Syntax
wfselect wfname[\pgname]

where wfname is the name of a workfile that has been loaded into memory. You may option-
ally provide the name of a page in the new default workfile that you wish to be made active.

Examples
wfselect myproject
wfselect myproject\page2

both change the default workfile to MYPROJECT. The first command uses the default active
page, while the second changes the page to PAGE2.

Cross-references
See Chapter 2. “Workfile Basics,” on page 29 of User’s Guide I for a discussion of workfiles.

See also pageselect (p. 554).

wfsnapshot Object Container, Data, and File Commands

Takes a manual snapshot of the current workfile.

Syntax
wfsnapshot(options) [label] [description]

Options
nocap Optional flag to NOT include captured commands in snap-
shot meta-data.

Both the label and description are optional arguments.

Examples
wfsnapshot “my label” “my description”
664—Chapter 17.Command Reference

wfstats Object Container, Data, and File Commands

Display the workfile statistics and summary view.

Syntax
wfstats [wfname]

displays the workfile statistics and summary view showing, for each page of the specified
workfile, the structure of the page, and a summary of the objects contained in the page. The
specified workfile must be open. If no workfile is specified, wfstats will display results for
the active workfile.

Examples
wfstats

displays the statistics view for the active workfile.


wfstats wf2

displays the statistics for the open workfile WF2.

Cross-references
See “Workfile Summary View” on page 65 of User’s Guide I for a description of the workfile
statistics and summary view.

wfunlink Object Container, Data, and File Commands

Break links in all link objects and auto-updating series (formulae) in the active workfile.

You should use some caution with this command as you will not be prompted before the
links and auto-updating series are converted.

Syntax
wfunlink

Examples
wfunlink

breaks links in all pages of the active workfile


wfuse—665

Cross-references
See Chapter 8. “Series Links,” on page 249 of User’s Guide I for a description of link objects,
and “Auto-Updating Series” on page 219 of User’s Guide I for a discussion of auto-updating
series.

See also Link::link (p. 530) and Link::linkto (p. 530) in the Object Reference.

See also pageunlink (p. 561) and unlink (p. 618) for page and object based unlinking,
respectively.

wfuse Object Container, Data, and File Commands

Activates a workfile. If the workfile is currently open in EViews, then it is selected to


become the default workfile. If the workfile is not currently open, it is opened.

Syntax
wfuse [path\]workfile_name[.wf1][\page_name]

The name of the workfile is specified as the argument to wfopen and may be followed by an
optional page name to specify a specific page in the workfile. If the workfile is not located in
the current default directory, and is not currently open in EViews, you should specify the
path of the workfile along with its name. If you do specify a path, you should also include
the .WF1 extension.

Examples
wfuse basics

activates the BASICS workfile. If BASICS is not currently open in EViews and is not located
in the current default directory, wfuse will error.
wfuse c:\mydata\basics.wf1

activates the BASICS workfile located in “c:\mydata”.


wfuse c:\mydata\basics.wf1\page1

activates the page named PAGE1 in the BASICS workfile located in “C:\MYDATA”.

Cross-references
See Chapter 2. “Workfile Basics,” on page 29 of the User’s Guide I for a discussion of work-
files.

See also wfopen (p. 640) and wfsave (p. 656).


666—Chapter 17.Command Reference

workfile Object Container, Data, and File Commands

Create or change workfiles.

No longer supported; provided for backward compatibility. This command has been
replaced by wfcreate (p. 634) and pageselect (p. 554).

write Object Container, Data, and File Commands

Write EViews data to a text (ASCII), Excel, or Lotus file on disk.

Creates a foreign format disk file containing EViews data. May be used to export EViews
data to another program.

Unless you need to write your workfile data in transposed or in Lotus form, we recommend
that you use the more powerful command for writing a workfile page documented in page-
save (p. 548).

Syntax
write(options) [path\]filename arg1 [arg2 arg3 …]

Follow the keyword by a name for the output file and list the series to be written. The
optional path name may be on the local machine, or may point to a network drive. If the
path name contains spaces, enclose the entire expression in double quotation marks.

Note that EViews cannot, at present, write into an existing file. The file that you select will,
if it exists, be replaced.

Options
Options are specified in parentheses after the keyword and are used to specify the format of
the output file.
prompt Force the dialog to appear from within a program.

File type
t=dat, txt ASCII (plain text) files.
t=wk1, wk3 Lotus spreadsheet files.
t=xls Excel spreadsheet files.

If you omit the “t=” option, EViews will determine the type based on the file extension.
Unrecognized extensions will be treated as ASCII files. For Lotus and Excel spreadsheet files
write—667

specified without the “t=” option, EViews will automatically append the appropriate exten-
sion if it is not otherwise specified.
ASCII text files
na=string Specify text string for NAs. Default is “NA”.
names (default) / [Write / Do not write] series names.
nonames
dates / nodates [Write / Do not write] dates/obs. “Dates” is the default
unless the “t” option for writing by series is used, in which
case “nodates” is the default.
d=arg Specify delimiter (default is tab): “s” (space), “c”
(comma).
t Write by series. Default is to write by obs with series in col-
umns.

Spreadsheet (Lotus, Excel) files


letter_number Coordinate of the upper-left cell containing data.
names (default) / [Write / Do not write] series names.
nonames
dates (default) / [Write / Do not write] dates/obs.
nodates
dates=arg Excel format for writing date: “first” (convert to the first
day of the corresponding observation if necessary), “last”
(convert to the last day of the corresponding observation).
t Write by series. Default is to write by obs with series in col-
umns.

Examples
write(t=txt,na=.,d=c,dates) a:\dat1.csv hat1 hat_se1

Writes the two series HAT1 and HAT_SE1 into an ASCII file named DAT1.CSV on the A
drive. The data file is listed by observations, NAs are coded as “.” (dot), each series is sepa-
rated by a comma, and the date/observation numbers are written together with the series
names.
write(t=txt,na=.,d=c,dates) dat1.csv hat1 hat_se1

writes the same file in the default directory.

Cross-references
See “Exporting to a Spreadsheet or Text File” on page 171 of User’s Guide I for a discussion.
See pagesave (p. 548) for a superior method of exporting workfile pages to foreign formats.
668—Chapter 17.Command Reference

See also read (p. 570).

xclose External Interface Commands

Close an open connection to an external application.

Syntax
xclose

xclose is used to close an open COM session with an external application.

Examples
xclose

closes the open connection.

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion.

See also xopen (p. 672), xget (p. 668), xput (p. 675), xrun (p. 677), and xlog (p. 671).

xget External Interface Commands

Retrieve data from an external application into an EViews object.

Syntax
xget(options) object @smpl sample

xget is used to retrieve data from an external COM application (support is currently pro-
vided for MATLAB and R). An existing connection to the external application must have
already been opened using xopen (p. 672). The xget command should be followed by the
name of the object to retrieve, followed by an optional @smpl keyword and a sample speci-
fication, or the name of a sample object. Including @smpl lets you specify the observations
into which the data will be retrieved.

Options
name=arg Specify the name of the object to be created in EViews. If
the name option is not specified, the created object will
have the same name as the external application object that
is being retrieved.
xget—669

wf=arg Specify the workfile into which the retrieved objects will be
placed. The specified workfile must be currently open
inside EViews. If the wf option is not specified, the objects
will be put into the current default workfile.
page=arg Specify the workfile page into which the retrieved objects
will be placed. If the page option is not specified, the
objects will be put into the current default page.
type=arg Specify the EViews object type to be created. arg can be
“series”, “alpha”, “matrix”, “vector”, “svector”, “coef”,
“sym”, “scalar” or “string”. If the type option is not set,
EViews will automatically decide which object type to cre-
ate.
mode = arg Merge options: “protect” (protect destination – only
(default=“merge”) retrieve values if destination does not already exist),
“merge” (prefer source -– merge only if source value is
non-missing), “mergedest” (prefer destination – merge
only if destination value is missing), “update” (replace all
destination values in the retrieval sample with source val-
ues), “overwrite” (replace all destination values in retrieval
sample with source values, and NAs outside of sample).

R-specific options
fdata=arg When reading a factor object, specifies how to read the fac-
tor data: as numbers (default), as labels (“labels”), as both
numbers and labels (“both”).
If “fdata=both”, the labels will be read into a valmap
object, and the valmap will be attached to the destination
series (the data target must be a series for this setting).
fmap=arg Name of the valmap object to hold the factor labels (when
“fdata=both”).
670—Chapter 17.Command Reference

fmode=arg Specifies settings for reading factor label data into a val-
map: merge with preference to the existing values in the
map (default), merge with preference to the factor map
values (“merge”), overwrite existing valmap definitions
(“overwrite”), do not alter an existing valmap (“protect”).
The default method adds definitions from the factor to an
existing valmap, retaining existing valmap entries that con-
flict with definitions from the factor.
“Merge” adds definitions from the factor to an existing val-
map, replacing conflicting valmap entries with definitions
from the factor.
“Overwrite” replaces an existing valmap specification with
the factor definitions.
“Protect” ensures that an existing valmap is not altered.

MATLAB-specific options
workspace=arg MATLAB environment in which to obtain the data: “base”
(default=“base”) (base workspace), “global” (global workspace).

Examples
xget X

retrieves an object “X” from the current open external application connection, and stores it
into the current default workfile.
xget(type=vector, name=x1) Ymat

retrieves the object named “Ymat” and stores it into the current default workfile as a vector
named X1.
xget(wf=mywf, type=series, name=x2) X @smpl 1990 1999

retrieves X and stores it in the MYWF workfile as a series called X2, where only the observa-
tions between 1990 and 1999 are filled in.

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion.

See also xopen (p. 672), xclose (p. 668), xput (p. 675), xrun (p. 677) and xlog (p. 671).
xoff—671

xlog External Interface Commands

Switch on or off the external application log inside EViews.

Syntax
xlog(arg)

xlog is used to switch on or off the external COM application log window inside EViews.
arg should be either “show” (to switch the log on), or “hide” (to switch it off).

Examples
xlog(hide)

switches off the log.

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion.

See also xopen (p. 672), xclose (p. 668), xget (p. 668), xput (p. 675), and xrun (p. 677).

xoff External Interface Commands

Turns off external command mode in an EViews program.

Every program line after XOFF will be treated as an EViews command.

Syntax
xoff

Examples
xopen(type=r)
xon
print(ls())
xoff
xclose

opens a connection to R, turns on external command mode, sends an R print command,


turns external command mode off, and finally closes the external connection.
672—Chapter 17.Command Reference

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion.

See also xon (p. 672), xopen (p. 672), xclose (p. 668), xget (p. 668), xput (p. 675), and
xrun (p. 677).

xon External Interface Commands

Turns on external command mode in an EViews program.

Turns on external command mode in an EViews program. Every program line after XON will
be sent directly to the external application (R or MATLAB) without the need to start the
command with XRUN. Call XOFF to turn this mode off.

Syntax
xoff

Examples
xopen(type=r)
xon
print(ls())
xoff
xclose

opens a connection to R, turns on external command mode, sends an R print command,


turns external command mode off, and finally closes the external connection.

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion.

See also xoff (p. 671), xopen (p. 672), xclose (p. 668), xget (p. 668), xput (p. 675), and
xrun (p. 677).

xopen External Interface Commands

Open a connection to an external application.

Syntax
xopen(options)
xopen—673

xopen is used to start a COM session with an external application, either R or MATLAB.
EViews can only have a single session open at a time; a session must be closed (see xclose
(p. 668)) before a new session can be opened.

Options
type=arg Set the type of connection to be opened. arg may be “r” (R)
or “m” (MATLAB).
keepcurrent If “type=” is the same as a currently open connection,
keep original connection since it is already open.
progid=arg (optional) Set the version of MATLAB or statconnDCOM to
which EViews connects when opening a session. If not
specified, EViews will use the default ProgID specified in
the global options.
nolog Do not open a session log window.
case=arg Specify the default case for objects in R or MATLAB using
xput (p. 675). If “case=” is not provided, the default case
specified in the global options will be assumed. Note that
once a connection has been opened, the case option cannot
be changed; you may however, use the “name=” option
when using xput (p. 675) to provide an explicit name.

Note that the MATLAB ProgIDs may be of particular interest as MATLAB (R2008a and later)
offers several distinct ways in which to connect to the server. The relevant ProgIDs are:
1. “MATLAB.Application”— this ProgID starts a command window version of MAT-
LAB that was most recently used as a server (might not be the latest installed ver-
sion of MATLAB).
2. “MATLAB.Application.Single”— same as (1) but starts a dedicated server so that
other programs looking to use MATLAB cannot connect to your instance.
3. “MATLAB.Autoserver”—starts a command window server using the most recent
version of MATLAB.
4. “MATLAB.Autoserver.Single”—same as (3) but starts a dedicated server.
5. “MATLAB.Desktop.Application”—starts the full desktop MATLAB as a server using
the most recent version of MATLAB.

Each ProgID may be amended to indicate a specific version of MATLAB. For example, using
the ProgID:
MATLAB.Desktop.Application.7.6
instructs EViews to use the full desktop MATLAB GUI for version R2008a (v7.6) as the Auto-
mation server.
674—Chapter 17.Command Reference

Examples
xopen(type=m)

opens a connection to MATLAB.


xopen(type=r, case=lower)

opens a connection to R and sets the default name-case to lower.


xopen(type=m, progid=MATLAB.Desktop.Application.7.9)

opens a connection to MATLAB 7.9 running with the full desktop GUI.

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion. See also “External Program Interface” on page 2557 of User’s Guide
I for global options setting.

See xclose (p. 668), xget (p. 668), xput (p. 675), xrun (p. 677), and xlog (p. 671).

xpackage External Interface Commands

Installs the specified R package in the current external R connection.

Syntax
xpackage(options) package_name

xpackage is only supported for external R connections (no MATLAB support) and is used to
verify that a specific R package has been installed. If the package is not found, it is down-
loaded and installed automatically. package_name should be the name of the R package
(case-sensitive).

Options
prompt If the specified package is not found, this option forces
EViews to warn the user that an R package is missing and
must be installed before continuing. By default, in an
EViews program, prompt is off. When running XPACKAGE
from the command window, prompt is always on.
repos=http://… Specifies which R repository URL to use to download the
package. If not specified, EViews will attempt to find the
current repo site in the current R profile. If not found, and
prompt is on, EViews will then ask the user to pick a repo
site from the standard R CRAN mirror list. Otherwise,
EViews will default to: https://cran.cnr.berkeley.edu
xput—675

Examples
xpackage rscproxy

verifies the existence of the rscproxy package. If not found, EViews will attempt to download
and install it.
xopen(prompt) forecast

verifies the existence of the forecast package. If not found, EViews will first prompt the user
with a timed dialog stating that the rscproxy must first be installed. Once the user clicks Yes
or the dialog times out (5 seconds), EViews will then attempt to download and install it.
xopen(repos= https://muug.ca/mirror/cran) GETS

verifies the existence of the GETS package. If not found, EViews will attempt to download
and install it from the specified repos link.

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion. See also “External Program Interface” on page 2557 of User’s Guide
I for global options setting.

See xclose (p. 668), xget (p. 668), xput (p. 675), xrun (p. 677), and xlog (p. 671).

xput External Interface Commands

Send an EViews object to an external application.

Syntax
xput(options) ob_list @drop ob1 @smpl sample

xput is used to push data from EViews to an COM external application (either R or MAT-
LAB). An existing connection to the external application must have already been opened,
using xopen.

ob_list should be a space delimited list of EViews objects to push into the application. An
asterisk (*) can be used as a wildcard. Objects that can be pushed include series, alphas,
matrices, syms, vectors, svectors, rowvectors, coefs, scalars and strings. if the object list con-
tains an object you do not wish to be pushed to the external application, you can use @drop
followed by the name of the object.

For series and alphas, you may enter a sample to specify which observations you wish to be
pushed, using @smpl followed by the sample specification or the name of a sample object.
676—Chapter 17.Command Reference

Options
name=arg Specify the name or names of the objects to be created in
the destination application. Multiple names may be speci-
fied using a wildcard or a space-delimited list of names.
Names specified using the name option are case-sensitive
so that destination objects will preserve the case of arg.
If the name option is not specified, the created objects will
have the same name as the EViews objects that are being
pushed, with the case determined by the case established
for the COM connection (see xopen (p. 672)).
mode=arg Merge options: “protect” (protect destination – only put
(default= values if destination does not already exist), “overwrite”
“overwrite”) (replace all destination values with source values, and
resize if necessary).
wf=arg Specify the workfile containing the objects to be pushed.
The specified workfile must be currently open inside
EViews. If the “wf=” option is not specified, the objects
will be taken from the current default workfile.
page=arg Specify the workfile page containing the objects to be
pushed. If the “page=” option is not specified, the objects
will be taken from the current default page.
map Write value-mapped series using map labels instead of
underlying values.

R-specific options
rtype=arg Specify the type of object to be created in R. arg can be
“vector”, “ts”, “data.frame” or “list”.

MATLAB-specific options
mtype =arg Specify the type of object to be created in MATLAB:
“matrix” (matrix object), “cell” (cell object).
workspace=arg MATLAB environment in which to place the data: “base”
(default=“base”) (base workspace), “global” (global workspace).

Examples
xopen(type=m)
xput(name=g) group01

opens a connection to MATLAB and then pushes the group GROUP01 to MATLAB, giving it
the name G.
xopen(type=r)
xrun—677

xput(page=page2, rtype=vector) x @smpl 1990 1999

Opens a connection to R and pushes the series X from page PAGE2 of the current default
workfile into a vector in R. Only the 10 observations for X from 1990 and 1999 are pushed
into R. X will be named in R using the name “X” with the default case specified in the global
options.
xopen(type=r, case=upper)
xput(rtype=data.frame, name=df1) x* @drop x2

Opens a connection to R and puts all objects whose name starts with “X”, apart from the
object X2, into a data frame, named “df1”. The names of the “X*” objects will be uppercased
in R.

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion. See also “External Program Interface” on page 2557 of User’s Guide
I for global options setting of the default case for names.

See also @xputnames (p. 1220), xopen (p. 672), xclose (p. 668), xget (p. 668), xrun
(p. 677), and xlog (p. 671).

xrun External Interface Commands

Run a command in an external application.

Syntax
xrun command

xrun is used to run a command in an external COM application (either R or MATLAB). An


existing connection to the external application must have already been opened using xopen.
xrun should be followed by the command you wish to run.

Examples
xopen(type=m, case=upper)
xput Y
xput XS
xrun beta = inv(XS'*XS)*XS'*Y

opens a connection to MATLAB, sends the series Y and the group XS to MATLAB, then runs
a command which will compute the least squares coefficients from a regression of Y on XS.

The commands
xopen(type=r, case=upper)
678—Chapter 17.Command Reference

xput(rtype=data.frame, name=cancer) age drug2 drug3 studytim


xrun z<-glm(STUDYTIM~AGE+1+DRUG2+DRUG3,
family=Gamma(link=log),data=cancer)

send data to R and estimate GLM model.

Note that the statconnDCOM package does not always automatically capture all of your R
output. Consequently, you may find that using xrun to issue a command that displays out-
put in R may only return a subset of the usual output to your log window. In the most
extreme case, you may see a simple “OK” message displayed in your log window. To instruct
statconnDCOM to show all of the output, you should use enclose your command inside an
explicit print statement in R. Thus, to display the contents of a matrix X, you must issue
the command
xrun print(X)

instead of the more natural


xrun X

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for a discussion.

See also xopen (p. 672), xclose (p. 668), xget (p. 668), xput (p. 675), and xlog (p. 671).
Chapter 18. Function Reference

The entries below form an alphabetical listing of the functions available in EViews. By func-
tions, we mean an expression that can (but need not) take arguments and that returns a
value in the form of a number, string, or object. The function arguments may be numeric or
alphanumeric, and may be specified using literal values, substitution or replacement vari-
ables, EViews objects, or values returned by other functions.

Typically, an EViews function may be identified by an initial “@” in the name, as in


“@mean” or “@movav”. There are, however, a handful of functions such as “log” or “exp”
for which both a “@” and a non-“@” form exist.

Functions in EViews may be grouped in a number of different ways. Some functions may be
characterized as element functions that work on scalar values or individual elements of
objects. Other functions produce descriptive statistics for data in series, groups, and matri-
ces. There are some functions which work on matrix objects as a whole, performing stan-
dard operations such as matrix multiplication, inversion, and factoring, while other
functions focus on alphanumeric data or operations involving dates.

Before proceeding to the function summaries and a full alphabetical listing, we offer brief
background on the nature of function arguments in EViews.

Function Arguments
Most of the functions you will use in EViews take arguments, where you will supply neces-
sary information to the function. In discussing various function types, it will be useful to
develop a simple framework for understanding the use of function arguments in EViews.

Some functions require that arguments correspond to a highly specific object types. For
example, the @eigenvalues (p. 864) function, which computes the eigenvalues of a sym-
metric matrix, requires a single sym and returns a vector. Similarly, the @wjoin (p. 1202)
function, which concatenates elements of an svector, requires a single svector argument,
and returns a string.

For other functions, arguments are valid for a wider range of object types. For example, the
single argument of the matrix @transpose (p. 1147) command may be a vector, rowvector,
or matrix object. In this case the function return type depends on the input type, with a vec-
tor returning a rowvector and vice versa, and an  n  m  matrix returning a  m  n 
matrix.

Lastly, for some functions, arguments can work with almost all types of input. Some, like
the absolute value function @abs (p. 713), work with any numeric input, including numeric
objects, literals and program replacement variables. Other functions, like the string length
680—Chapter 18.Function Arguments

function @len (p. 943) work with any alphanumeric input, including string vectors, literals
and program substitution variables. In these cases, the return type will generally depend on
the input type.

When functions with flexible types have multiple arguments, you can often provide any
appropriate values for the function argument and if possible, EViews will adjust the evalua-
tion and output accordingly.

Consider, for example the @left (p. 942) function which returns the n left-most characters
in a string S . The first argument of the function corresponds to an alphanumeric S , and the
second argument is a numeric n .

For this function, EViews will return different types of results for different combinations of
valid S and n argument types. The command
= @left("When in the course", 4)

returns the string “When” which is displayed in the EViews status line.

If A is a vector object containing the values 1, 2, 3, 4,


svector s1 = @left("When in the course", A)

will produce an svector S1 containing the strings “W”, “Wh”, “Whe”, and “When”. In this
case, EViews evaluates the function repeatedly using the literal value “When in the course”
for S paired with each of the four values of A for n .

Alternately, if V is a 4-element svector,


svector s2 = @left(V, 4)

will return a 4-element svector S2 containing the left-most 4 characters of the corresponding
elements of V.

Lastly,
svector s3 = @left(V, A)

will pair the elements of the svector V and vector A as defined above, returning an svector
containing the first character of the first element of V, the first two characters of the second
element of V, the first three characters of the third element of V, and the first four characters
of the fourth element of V.

To take another example, suppose we wish to specify a string date, find the corresponding
underlying date number, manipulate that number to add various numbers of weeks, and
then find a string representation of the new date number.

We can now perform a vectorized version of this operation which finds a string representa-
tion for 11 weekly days beginning at an initial scalar date:
wfcreate d7 2000 202
Function Summaries—681

vector weeks = @seq(0, 1, 11)


string startdate = "May 1, 2000"
svector enddates = @datestr(@dateadd(@dateval(startdate), weeks,
"W"))

This operation uses the @dateval (p. 825) function to convert the initial string into a date
number, the @dateadd (p. 815) function to find the date numbers associated with the initial
date number and the following 10 weeks, and the @datestr (p. 824) function to convert the
result back into a string.

Function Summaries
Operators
Strictly speaking, operators in EViews are not functions as defined above, though they share
a number of characteristics. As the name suggests, operators “operate” on data elements
and return results.
• (“+”) Addition: adds two numeric values or concatenates strings.
• (“–”) Subtraction: subtracts the second numeric value from the first value.
• (“*”) Multiplication: multiplies two numeric values.
• (“/”) Division: divides the first numeric value by the second value.
• (“^”) Raise to Power: raises the first numeric value to the power of the second value.
• (“>”) Greater Than: returns 1 if the first value is greater than the second value and 0
otherwise.
• (“>=”) Greater Than or Equal To: returns 1 if the first value is greater than or equal to
the second value and 0 otherwise.
• (“<”) Less Than: returns 1 if the first value is less than the second value and 0 other-
wise.
• (“<=”) Less Than or Equal To: returns 1 if the first value is less than or equal to the
second value and 0 otherwise.
• (“=”) Equal To: returns 1 if the first value is equal to the second value and 0 other-
wise.
• (“<>”) Not Equal To: returns 1 if the first value is not equal to the second value and 0
otherwise
• (“and”) Logical And: returns 1 if both the first and the second condition are true, and
0 otherwise.
682—Chapter 18.Function Summaries

• (“or”) Logical Or: returns 1 if either the first or the second condition is true, and 0
otherwise.

There are a few key points to bear in mind:


• The precedence of evaluation is listed in “Operators” on page 195. You can enforce
order-of-evaluation using parentheses.
• When applied to series or alpha object expressions, the operations are performed for
each observation in the current sample.
• When applied to matrix expressions the operations are performed on all of the obser-
vations. Note that the boolean comparisons will return 0 if any element of the test
fails. For element tests, see “Matrix Element Functions” on page 709.
• The operators propagate missing values. EViews provides functions that employ spe-
cial rules for handling missing values: @eqna (p. 873), @isna (p. 927), @neqna
(p. 1010), @eeqna (p. 862), @eisna (p. 865), and @eneqna (p. 871). See “Missing Val-
ues” on page 203 for discussion.

Element Functions
Many EViews functions may be termed element functions since they takes arguments that
correspond to numeric or alphanumeric scalar values, and return a single numeric or alpha-
numeric value.

EViews generalizes this basic behavior to arguments involving the elements of various data
objects including series and alpha series, and the various matrix objects including vectors,
matrices, and svectors.

Scalar Arguments
If the argument is a literal or scalar value, EViews will perform the computation and return a
scalar value. To take a simple example, consider the log and @log functions, which both
compute the natural logarithm of the numeric argument, and the @length and @left func-
tions, which compute the length and return the left-most characters, respectively, of an
alphanumeric (string) argument.

The commands,
= @log(3.2)
scalar s1= @log(1.2)
!s2 = log(s1)

all compute natural logarithms of the scalar numeric argument. The first command displays
the results in the EViews status line, the second creates a scalar object S1, and the third
assigns the value to a program replacement variable !S2.

Similarly, for the individual string arguments,


Function Summaries—683

= @length("abcd")
string start = "When in the course"
string s4 = @left(start, 4)
%s4 = @left(start, 4)

the first command displays the number 4 in the status line, and the third and fourth lines
both return the string “When”, assigning the result to a string object, and a replacement
variable, respectively.

Workfile Data Arguments


If the argument is a series, alpha, or group, EViews evaluates an element function using the
value for each observation in the current workfile sample, and returns a series or alpha
depending on the function return type. In essence, the underlying function is evaluated
repeatedly, in a loop over all observations in the sample.

The commands
wfcreate q 2001 2025
series y = rnd
smpl 2010 2020
series tr = @exp(y)

creates a quarterly workfile from 2001q1 to 2025q4, creates a random series Y, sets the sam-
ple to 2010q1 to 2020q4, and assigns the results from the @exp function to the new series TR
over that subsample. Note that since the TR series is newly created, it will have NA values
for all observations outside of 2010q1 to 2020q4.

Similarly, the commands


wfcreate q 2001 2025
alpha a = "<missing>"
smpl 2010 2020
alpha a = @chr(@trend)

initialize the alpha series A to contain the string value “<missing>” for all observations in
the workfile, then sets the 2010q1 to 2020q4 subsample of A to contain the results from the
@chr function evaluated at the @trend values.

Matrix Arguments
For matrix objects (broadly defined to include svectors) EViews evaluates the function for
each element of the object and returns an object of the appropriate type and corresponding
size.

Consider the commands


vector v1 = @fill(1, 2, 3)
684—Chapter 18.Function Summaries

vector vector logv1 = @log(v1)

which creates a 3-element vector V1 containing the values 1, 2, and 3, then employs the ele-
ment function @log to create a 3-element vector LOGV1, with values 0, log(2), and log(3).

Further, the commands


matrix m1 = @mnrnd(3, 2)
matrix absm1 = @abs(m1)

fills a 3  2 matrix M1 with standard normal random numbers, then uses the element func-
tion @abs to create the 3  2 matrix LOGM1 containing the absolute values of the elements
of M1 in corresponding positions. Note also that these two commands may be combined
into the single line:
matrix absm1 = @abs(@mnrnd(3, 2))

Similarly, the commands


svector s1 = @sfill("apple", "pear", "orange")
vector lens1 = @length(s1)

sets up the svector by creating a 3-element vector containing the strings “apple”, “pear”,
and “orange” and then uses the element function @length to create a 3-element vector
LENS1 with values 5, 4, and 6.

Summary
Below we attempt to categorize the element functions into useful groupings. Naturally, the
categorizations are not the only ones possible, but we have tried to provide groupings that
will aid you in locating a function of interest. Because there are multiple ways to group the
information, functions may appear in more than one category.

Numeric Constants
@pi...................... Pi – ratio of a circle's circumference to its diameter ( p ) (p. 1037).
@log2pi ............... Natural logarithm of 2p (p. 949).

Basic Math Functions


@abs.................... Absolute value (p. 713).
abs ....................... Absolute value (p. 713).
@binom ............... Binomial coefficient (p. 726).
@binomlog .......... Natural logarithm of the binomial coefficient (p. 726).
@ceil ................... Smallest number greater than or equal to (with optional precision)
(p. 737).
@cloglog.............. Complimentary log-log function (p. 749).
@exp ................... Exponential function (p. 879).
exp....................... Exponential function (p. 879).
Function Summaries—685

@expm1 ...............Exponential function minus (p. 880).


@fact....................Factorial function (p. 881).
@factlog ...............Natural logarithm of the factorial function (p. 882).
@floor ..................Largest number less than or equal to with optional precision
(p. 887).
@isna ...................Test for missing value (p. 927).
@log.....................Natural logarithm function (p. 947).
log ........................Natural logarithm function (p. 947).
@log10 .................Base-10 logarithm function (p. 948).
@log1mexp...........Natural logarithm function of 1 minus exponential of argument
(p. 948).
@log1p .................Natural logarithm function of 1 plus argument (p. 949).
@logx ...................Arbitrary base logarithm function (p. 951).
@logit...................Logistic transform (p. 950).
@mod...................Floating point remainder (p. 983).
@pow...................Power function (p. 1041).
@pow1pm1 ..........Power function of 1 plus argument, minus 1 (p. 1041).
@powm1 ..............Power function, minus 1 (p. 1042).
@round ................Nearest integer, or value at given precision (p. 1088).
sqr ........................Square root (p. 1116).
@sqrt....................Square root (p. 1117).
@sign ...................Sign of number (p. 1112).

Utility Functions
@between.............Dummy variable for value within range of values (p. 725).
@bounds ..............Bounded values (p. 727).
@iif ......................Recode values by condition (conditional value) (p. 915).
@inlist..................Dummy variable for value in list (p. 921).
@nan....................Recode missing values (p. 1009).
@recode ...............Recode value by condition (p. 1068).

Trigonometric Functions
@acos...................Arc cosine (in radians) (p. 714).
@asin ...................Arc sin (in radians) (p. 717).
@atan...................Arc tangent (in radians) (p. 718).
@cos ....................Cosine of argument specified in radians (p. 769).
@sin.....................Sine function in radians (p. 1112).
@tan ....................Tangent of argument specified in radians (p. 1144).
686—Chapter 18.Function Summaries

Statistical Distributions
The following functions provide access to the density or probability functions, cumulative
distribution, quantile functions, and random number generators for a number of standard
statistical distributions.

Most of the distributions support four different function types:

Function Type Beginning of Name


Cumulative distribution (CDF) @c
Density or probability @d
Quantile (inverse CDF) @q
Random number generator @r

though some distributions support only a subset of the types. The listing below may also
show related functions.

Note that the CDFs are assumed to be right-continuous: F X  k   Pr  X  k  . The quantile


functions q X  p   q will return the smallest value q where the CDF evaluated at q
equals or exceeds the probability of interest: F X  q   p . The inequalities are only relevant
for discrete distributions.

Many of the cumulative distribution functions take an optional argument at the end of the
argument list. Non-zero values tell EViews to compute the upper tail of the CDF.

Discrete Distributions
Binomial
@cbinom ............. Binomial cumulative probability function (p. 735).
@dbinom ............. Binomial probability function (p. 828).
@qbinom ............. Binomial distribution quantile (p. 1046).
@rbinom.............. Binomial distribution random draw (p. 1067).

Negative Binomial
@cnegbin............. Negative binomial cumulative probability function (p. 753).
@dnegbin ............ Negative binomial probability function (p. 845).
@qnegbin ............ Negative binomial distribution quantile (p. 1053).
@rnegbin ............. Negative binomial distribution random draw (p. 1087).

Poisson
@cpoisson............ Poisson cumulative probability function (p. 770).
@dpoisson ........... Poisson probability function (p. 846).
@qpoisson ........... Poisson distribution quantiles (p. 1055).
@rpoisson ............ Poisson distribution random draw (p. 1092).
Function Summaries—687

Continuous Distributions
Beta
@cbeta .................Beta cumulative distribution function (p. 734).
@dbeta .................Beta distribution probability density (p. 828).
@qbeta .................Beta distribution quantile (p. 1045).
@rbeta..................Beta distribution random draw (p. 1067).

Bivariate Normal
@cbvnorm ............Bivariate normal cumulative distribution function (p. 735).
@dbvnorm............Bivariate normal probability density function (p. 829).

Chi-Square
@cchisq................Chi-square cumulative distribution function (p. 736).
@chisq .................Upper tail of the Chi-square cumulative distribution function
(p. 742).
@dchisq ...............Chi-square probability density function (p. 830).
@qchisq ...............Chi-square distribution quantile (p. 1047).
@rchisq ................Chi-square distribution random draw (p. 1068).

Exponential
@cexp ..................Exponential cumulative distribution function (p. 738).
@dexp ..................Exponential probability density function (p. 837).
@qexp ..................Exponential distribution quantile (p. 1047).
@rexp...................Exponential distribution random draw (p. 1072).

Extreme Value (Type I-minimum)


@cextreme............Extreme value (Type I-minimum) cumulative distribution function
(p. 739).
@dextreme ...........Extreme value (Type I-minimum) distribution function (p. 837).
@qextreme ...........Extreme value (Type I-minimum) distribution quantile (p. 1048).
@rextreme ............Extreme value (Type I-minimum) distribution random draw
(p. 1072).

F-distribution
@cfdist .................F-distribution cumulative distribution function (p. 739).
@dfdist .................F-distribution probability density function (p. 838).
@fdist...................Upper tail of F-distribution (p. 882).
@qfdist .................F-distribution quantile (p. 1048).
@rfdist .................F-distribution random draw (p. 1073).

Gamma
@cgamma.............Gamma cumulative distribution function (p. 741).
688—Chapter 18.Function Summaries

@dgamma............ Gamma probability density function (p. 838).


@qgamma............ Gamma distribution quantile (p. 1050).
@rgamma ............ Gamma distribution random draw (p. 1074).

Generalized Error
@cged.................. Generalized error cumulative distribution function (p. 742).
@dged ................. Generalized error probability density function (p. 839).
@qged ................. Generalized error distribution quantile (p. 1050).
@rged .................. Generalized error distribution random draw (p. 1074).

Inverse Wishart
@diwish .............. Inverse Wishart probability density function (p. 840).
@riwish ............... Inverse Wishart random draws (p. 1079).

Laplace
@claplace............. Laplace cumulative distribution function (p. 747).
@dlaplace ............ Laplace probability density function (p. 841).
@qlaplace ............ Laplace distribution quantile (p. 1051).
@rlaplace............. Laplace distribution random draw (p. 1080).

Logistic
@clogistic ............ Logistic cumulative distribution function (p. 748).
@dlogistic ............ Logistic probability density function (p. 843).
@logit .................. Logistic transform (p. 950).
@qlogistic ............ Logistic distribution quantile (p. 1052).
@rlogistic............. Logistic distribution random draw (p. 1081).

Log Normal
@clognorm .......... Log normal cumulative distribution function (p. 749).
@dlognorm .......... Log normal probability density function (p. 843).
@qlognorm .......... Log normal distribution quantile (p. 1052).
@rlognorm........... Log normal distribution random draw (p. 1082).

Multivariate Normal
@dmvnorm .......... Multivariate normal probability density function (p. 844).
@rmvnorm .......... Multivariate normal random draws (p. 1085).

Normal
@cnorm ............... Standard normal cumulative distribution function (p. 753).
@dnorm............... Standard normal probability density function (p. 845).
@logcnorm .......... Natural logarithm of standard normal cumulative distribution
(p. 950).
Function Summaries—689

@qnorm ...............Standard normal distribution quantile (p. 1054).


@rnorm ................Standard normal distribution random draw (p. 1087).

Pareto
@cpareto ..............Pareto cumulative distribution function (p. 769).
@dpareto ..............Pareto probability density function (p. 846).
@qpareto ..............Pareto distribution quantile (p. 1054).
@rpareto...............Pareto distribution random draw (p. 1092).

t-distribution
@ctdist .................Student’s t cumulative distribution function (p. 775).
@dtdist .................Student’s t probability density function (p. 847).
@tdist...................Tail probabilities of the Student’s t distribution (p. 1144).
@qtdist .................Student’s t distribution quantile (p. 1056).
@rtdist .................Student’s t distribution random draw (p. 1099).

Uniform
@cunif..................Uniform cumulative distribution function (p. 806).
@dunif .................Uniform probability density function (p. 849).
@qunif .................Uniform distribution quantile (p. 1059).
@runif ..................Uniform distribution random draw (p. 1100).

Weibull
@cweib ................Weibull cumulative distribution function (p. 808).
@dweib ................Weibull probability density function (p. 855).
@qweib ................Weibull distribution quantile (p. 1060).
@rweib.................Weibull distribution random draw (p. 1104).

Wishart
@dwish ................Wishart probably density function (p. 856).
@rwish.................Wishart random draw (p. 1104).

Financial Functions
The following functions perform calculations commonly employed in financial analysis.
@fv ......................Future value of annuity payments and (optional) initial lump sum
receipt (p. 889).
@nper ..................Number of periods for annuity to pay given present value (p. 1013).
@pv......................Present value of annuity receipts and (optional) final lump sum
receipt (p. 1044).
@pmt ...................Payment amount required for annuity to pay given present value
(p. 1040).
690—Chapter 18.Function Summaries

@rate................... Discount rate required for annuity to yield given present value
(p. 1066).

Special Functions
EViews provides a number of functions for evaluating special mathematical values such as
Euler’s constant. For further details on special functions, see the extensive discussions in
Temme (1996), Abramowitz and Stegun (1964), and Press, et al. (1992).
@beta .................. Beta integral (Euler integral of the second kind) (p. 722).
@betainc.............. Incomplete beta integral (p. 723).
@betaincder ......... Derivative of the incomplete beta integral (p. 723).
@betaincinv ......... Inverse of the incomplete beta integral (p. 724).
@betalog.............. Natural logarithm of the beta integral (p. 725).
@digamma........... First derivative of the natural log gamma function (p. 839).
@erf..................... Error function (Gauss error function) (p. 876).
@erfc ................... Complementary (Gauss) error function (p. 877).
@gamma.............. (Complete) gamma function (p. 891).
@gammader......... First derivative of the gamma function (p. 892).
@gammainc ......... Incomplete gamma function (p. 892).
@gammaincder .... Derivative of the incomplete gamma integral (p. 893).
@gammaincinv .... Inverse of the incomplete gamma function (p. 894).
@gammalog ......... Natural logarithm of the gamma function (p. 894).
@psi .................... First derivative of the natural log of the gamma function (p. 1043).
@trigamma .......... Second derivative of the natural log gamma function (p. 1152).

References
Abramowitz, M. and I. A. Stegun (1964). Handbook of Mathematical Functions with For-
mulas, Graphs, and Mathematical Tables, New York: Dover Publications.
Press, W. H., S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery (1992). Numerical
Recipes in C, 2nd edition, Cambridge University Press.
Temme, Nico M. (1996). Special Functions: An Introduction to the Classical Functions of
Mathematical Physics, New York: John Wiley & Sons.

Date Functions
@dateadd............. Date number after applying offset (p. 815).
@datediff ............. Difference between two date numbers (p. 817).
@dateceil ............. Last possible date in a time period (p. 819).
@datefloor ........... Earliest possible date in a time period (p. 820).
@datenext............ First possible date in the next time period (p. 821).
@datepart ............ Extract part of a date number (p. 823).
@datestr .............. String representation of a date number (p. 824).
Function Summaries—691

@dateval ..............Date number associated with a string representation of a date


(p. 825).
@localt .................Convert UTC (Coordinated Universal Time) to local time (p. 946).
@makedate...........Convert numeric representation of a date to date number (p. 960).
@now...................Current time date number (p. 1013).
@strnow...............String representation of the current date and time (p. 1132).
@time...................Current time as a string (p. 1146).
@tz ......................Convert time in source time zone to destination time (p. 1155).
@tzlist ..................Available time zone specifications (p. 1155).
@tzspec ................Time zone specification (p. 1156).

String Functions
@addquotes ..........Enclose string in quotation marks (p. 715).
@asc.....................ASCII value of character (p. 717).
@chr ....................ASCII value to string character (p. 744).
@iif ......................Recode values by condition (conditional value) (p. 915).
@inlist..................Dummy variable for value in list (p. 921).
@insert.................Insert string into string (p. 923).
@instr ..................Find position of substring in a string (p. 924).
@isempty .............Test for empty string (p. 926).
@isna ...................Test for missing value (p. 927).
@left ....................Left-hand characters in a string (p. 942).
@len.....................Length of a string (p. 943).
@length................Length of a string (p. 944).
@lower.................Lowercase representation of a string, or lower triangular matrix of a
matrix (p. 951).
@ltrim ..................Trim left-whitespace from string (p. 953).
@mid ...................Substring in middle or from middle to end of string (p. 974).
@nan....................Recode missing values (p. 1009).
@recode ...............Recode value by condition (p. 1068).
@replace...............Replace substring in string (p. 1070).
@right ..................Right substring of string (p. 1075).
@rinstr .................Find substring position in string (p. 1078).
@rtrim..................Trim right whitespace of string (p. 1100).
@str .....................String representation of number (p. 1123).
@strdate ...............String corresponding to the date of the observation (p. 1128).
@stripcommas ......Remove leading and trailing commas surrounding string (p. 1129).
@stripparens.........Remove paired leading and trailing parentheses surrounding string
(p. 1130).
692—Chapter 18.Function Summaries

@stripquotes ........ Remove paired double-quotation marks surrounding string


(p. 1131).
@strlen ................ Length of string (p. 1132).
@trim .................. Trim left and right whitespace from string (p. 1153).
@upper ................ Uppercase representation of a string; or upper triangular matrix of a
matrix (p. 1171).
@val .................... Number from a string (p. 1175).
@wcount ............. Number of words in the string list (p. 1188).
@wcross .............. String with words in first list crossed with second (p. 1188).
@wdelim ............. Replace delimiters in string (p. 1189).
@wdrop ............... Drop words from string list (p. 1191).
@wfind................ Find location of word (case-sensitive) in string list (p. 1196).
@wfname ............ String containing name of current workfile (p. 1198).
@wfindnc ............ Find location of word (not case-sensitive) in string list (p. 1197).
@winterleave ....... Interleave words of two string lists (p. 1200).
@wintersect ......... Intersection of words in two string lists (p. 1201).
@wjoin ................ Extract elements of an Svector to a string (p. 1202).
@wkeep............... Keep subset of words in string list (p. 1202).
@wleft ................. Left-most words of string list (p. 1203).
@wmid ................ Middle or middle to end words of a string list (p. 1206).
@wnotin .............. Words not in a string list (p. 1207).
@word................. Single word from a string list (p. 1208).
@wordq ............... Single word from a string list, preserving quotes (p. 1209).
@wread ............... Read contents of text file into a string (p. 1210).
@wreplace ........... Replace characters in each word in a string list (p. 1211).
@wrfind............... Find location of a word (case-sensitive) in a string list searching
from end (p. 1212).
@wrfindnc ........... Find location of a word (not case-sensitive) in a string list searching
from end (p. 1213).
@wright............... Right-most words of a string list (p. 1214).
@wsort ................ Sorted list of words in a string list (p. 1215).
@wsplit ............... Create string vector from words in a string list (p. 1216).
@wunion ............. Union of words in two string lists (p. 1216).
@wunique ........... Remove duplicate words in string list (p. 1217).

Basic Statistics
EViews offers basic statistics functions which compute statistical summaries using the data
in various EViews objects. Different functions support different types of source objects, with
slight differences in how the function is computed depending on type of source.
Function Summaries—693

Some statistics functions work with objects containing numeric data. Most of these func-
tions will work with any object that contains numbers. You may, for example, compute the
mean of series data using @mean (p. 971), the standard deviation of data in a vector using
@stdev (p. 1117), the trend coefficient from the regression of all of the data in a matrix on
an intercept and trend using @trendcoef (p. 1151), or the correlation matrix of data in a
group of series using @cor (p. 766).

Other functions work with objects containing both numeric and string data. For example,
you may use @max (p. 965) to identify the last sorted value, or @first (p. 886) to find the
first non-missing or empty element of series, vector, coef, rowvector, alpha, or svector data.

Crucially, for basic statistics computed using series, alpha, or group data, most EViews func-
tions will default to using data in the current workfile sample. You generally may provide an
alternate sample specification, enclosed in double quotes, as the last argument in the func-
tion. For vector, svector, and matrix computation using functions, EViews will use all of the
relevant data in the object.

Where summaries of matrices are allowed, EViews uses all of the elements of the matrix, by
vectorizing the matrix before performing the computation. Special functions are available if
you wish to perform individual computations for each of the columns of a matrix (“Sum-
mary,” on page 684).

For basic descriptive statistics, missing values, either in the form of numeric NAs or empty
strings, are ignored.

Basic Statistics
@columns ............Number of columns in matrix object or group (p. 762).
@cor.....................Correlation of two vectors or series, or between the columns of a
matrix or series in a group (p. 766).
@cov ....................Covariance (non-d.f.corrected) of two vectors or series, or between
the columns of a matrix or series in a group (p. 767).
@covp ..................Covariance (non-d.f. corrected) of two vectors or series, or between
the columns of a matrix or series in a group (p. 767).
@covs...................Covariance (d.f. corrected) of two vectors or series, or between the
columns of a matrix or series in a group (p. 769).
@first ...................The first non-missing value in the vector or series (p. 886).
@gmean ...............Geometric mean (p. 896).
@hmean ...............Harmonic mean (p. 900).
@ifirst ..................Index of the first non-missing value in the vector or series (p. 914).
@ilast ...................Index of the last non-missing value in the vector or series (p. 915).
@imax..................Index of maximum value (p. 915).
@imaxes...............Indices of maximum value (multiple) (p. 917).
@imin ..................Index of minimum value (p. 918).
694—Chapter 18.Function Summaries

@imins ................ Indices of minimum value (multiple) (p. 918).


@inner................. Inner product (p. 922).
@intercept ........... Intercept from a trend regression (p. 925).
@kurt .................. Kurtosis (p. 936).
@last ................... The last non-missing value in the vector or series (p. 940).
@mae .................. Mean of absolute error (difference) between series (p. 959).
@mape ................ Mean absolute percentage error (difference) between series
(p. 963).
@max .................. Maximum value (p. 965).
@maxes ............... Maximum values (multiple) (p. 966).
@mean ................ Arithmetic mean (p. 971).
@median ............. Median (p. 973).
@min................... Minimum value (p. 975).
@mins ................. Minimum values (multiple) (p. 976).
@mse................... Mean of square error (difference) between series (p. 1000).
@nas ................... Number of missing observations (p. 1009).
@norm ................ Norm of series or matrix object (p. 1012).
@obs ................... Number of observations (p. 1015).
@prod.................. Product (p. 1042).
@quantile ............ Empirical quantile (p. 1057).
@rmse ................. Root of the mean of square error (difference) between series
(p. 1084).
@skew................. Skewness (p. 1113).
@smape ............... Symmetric mean absolute percentage error (difference) between
series (p. 1114).
@stdev................. Sample standard deviation (d.f. adjusted) (p. 1117).
@stdevp ............... Population standard deviation (no d.f. adjustment) (p. 1118).
@stdevs ............... Sample standard deviation (d.f. adjusted) (p. 1119).
@stdize................ Standardized data (using sample standard deviation) (p. 1121).
@stdizep .............. Standardized data (using population standard deviation) (p. 1122).
@sum .................. Arithmetic sum (p. 1140).
@sumsq ............... Arithmetic sum of squares (p. 1136).
@theil .................. Theil inequality coefficient (difference) between series (p. 1145).
@trendcoef........... Trend coefficient from detrending regression (p. 1151).
@trmean .............. Trimmed mean (p. 1154).
@uniquevals ........ Vector or svector of unique values of object (p. 1169).
@valcount............ Number of matching values (p. 1178).
@var.................... Population variance (no d.f. adjustment) (p. 1179).
@varp .................. Population variance (no d.f. adjustment) (p. 1179).
Function Summaries—695

@vars ...................Sample variance (d.f. adjusted) (p. 1181).

Series Utility
The following functions facilitate working with all of the observations of series and alpha
data in a workfile.
@bridge................Copy of series using the current or preceding non-missing value
(p. 727).
@cagr ...................Compound annual growth rate of series (in decimal fraction)
(p. 732).
d...........................Difference (time-series) functions for series (p. 812).
@demean .............Compute deviations from the mean of the data object (p. 834).
@demeanby..........Compute deviations from the mean of the series by group (p. 835).
@detrend ..............Compute deviations from the trend of the data object (p. 836).
dlog ......................Difference functions for natural logarithm of a series (p. 842).
@dupselem...........Identifier for the observation within the set of duplicates (p. 851).
@dupsid ...............Identifier for the duplicates group for the observation (p. 852).
@dupsobs .............Number of observations in the corresponding duplicates group
(p. 853).
@eqna ..................Test for equality of data objects, treating NAs and null strings as
ordinary and not missing values (p. 873).
@fracdiff...............Fractional difference of series data (p. 889).
@inv ....................Reciprocal function (p. 925).
@lag .................. n-th order lag function (p. 939).
@neqna ................Inequality test (NAs and blanks treated as values, not missing val-
ues) (p. 1010).
@pc......................One-period percentage change (in percent) (p. 1031).
@pca ....................One-period percentage change, annualized (in percent) (p. 1031).
@pccagr ...............Annualized growth rate (in percent) (p. 1032).
@pch....................One-period percentage change (in decimal fraction) (p. 1033).
@pcha ..................One-period percentage change, annualized (in decimal fraction)
(p. 1033).
@pchy ..................One-year percentage change (in decimal fraction) (p. 1034).
@pctiles................Percentile values (p. 1035).
@pcy ....................One-year percentage change, (in percent) (p. 1036).
@pmax .................Pairwise maximum (p. 1039).
@pmin .................Pairwise minimum (p. 1039).
@ranks .................Ranking of values (p. 1064).
@stdize ................Standardized data (using sample standard deviation) (p. 1121).
@stdizep...............Standardized data (using population standard deviation) (p. 1122).
696—Chapter 18.Function Summaries

@trend................. Trend series (p. 1148).


@trendbr ............. Trend series with break (p. 1149).
@trendc ............... Trend series using calendar dates (p. 1150).

Workfile Functions
EViews workfile functions provide information about each observation of a workfile based
on the structure of the workfile.

These functions may be viewed in two ways:


• First, the workfile functions are virtual series available that can be used wherever a
regular series may be used.
• Alternatively, the workfile functions may be thought of as special functions that
depend on two implicit arguments: the workfile within which the function is being
used, and the observation number within this workfile for which to return a value.
For example, the @after (p. 716) function, which takes a single string date argument,
may be thought of as taking a string date argument, and implicit arguments for the
current workfile, and each observation in the workfile.

Since workfile functions are based on the structure of a workfile, they may only be used in
operations where a workfile is involved. Workfile functions may be used in statements that
generate series in a workfile, in statements that set the workfile sample, and in expressions
used in estimating an equation using data in a workfile.

Observation Functions
@after.................. Indicators for whether observation postdates a date (p. 716).
@before ............... Indicator for whether observation precedes a date (p. 721).
@cellid ................ Within cross-section identifier series for panel workfile observation
(p. 737).
@crossid .............. Cross-section identifier series for panel workfile observation
(p. 772).
@date .................. Date number of observation (p. 814).
@day ................... Day of observation (p. 826).
@daycount........... Number of days of week in observation (p. 827).
@during............... Indicator of whether an observation is between two dates (p. 854).
@event ................ Event identifier for observation (p. 878).
@enddate............. Last possible date of observation (p. 870).
@holiday ............. Holiday identifier for observation (p. 901).
@holidayset ......... Multiple holiday identifiers for observation (p. 905).
@hour ................. Hour of the day of the observation (integer) (p. 910).
@hourf ................ Hour of the date of the observation (floating point) (p. 910)
Function Summaries—697

@isperiod .............Is this the first observation matching the specified period (p. 930).
@minute...............Minute of the hour of the observation (p. 978).
@month ...............Month of the year of the observation (p. 983).
@obsid .................Sequential observation index for the observation (p. 1016).
@pageinidx...........Indicators for whether each observation in the workfile page is in
an index (p. 1028).
@quarter ..............Quarter of the year of the observation (p. 1059).
@seas ...................Seasonal dummy variable (p. 1109).
@second ...............Seconds of the minute of the observation (p. 1109).
@weekday ............Day of the week of the observation (p. 1192).
@year...................Year of the observation (p. 1223).

Utility Functions
@dtoo...................Observation number in the workfile associated with a date string
(p. 847).
@ispanel...............Is the current workfile page panel structured (p. 929).
@obsrange............Number of observations in the workfile page (p. 1017).
@obssmpl .............Number of observations in the workfile sample (p. 1017).
@otod...................Workfile observation to date string (p. 1019).
@otods .................Sample observation to date string (p. 1020).
@pagecount ..........Number of pages in workfile (p. 1024).
@pageexist ...........Does a page exist in the workfile (p. 1024).
@pagefreq ............Frequency specification for the workfile page (p. 1025).
@pageids ..............Workfile page observation identifiers (p. 1026).
@pageidx..............Index vector of the specified observations (p. 1027).
@pagelist..............List of pages in workfile (p. 1028).
@pagename ..........Name of active workfile page (p. 1028).
@pagerange ..........Range specification of active workfile page (p. 1029).
@pagesmpl ...........Sample specification in active workfile page (p. 1030).
@pagesmplidx ......Index vector of observations in the current sample (p. 1030).

Rolling (Moving) Statistics


You may compute rolling (moving) statistics that compute summary statistics for a moving
window of values in a series object, producing one value for each observation in the work-
file. EViews offers functions for computing moving sums, averages, sums-of-squares, vari-
ances, standard deviations, minimums, maximums, medians, skewness, and kurtosis for
single series, and correlations, covariances, and inner products between series.

The rolling statistics may be divided into two classes. The first set of rolling statistics, with
names beginning with “@mov”, propagate missing values. The second set with names
698—Chapter 18.Function Summaries

beginning with “@m” do not propagate missing values. This class of functions acts like
basic summary statistics by removing NAs as necessary.

In general, rolling statistics in EViews are computed on a trailing basis so that a 5-period
moving average for a given period is computed using the current and four lagged values of
the data.
• If you wish to center a moving window computation, you may perform the calcula-
tion using a lead of the data. Thus, “@movav(y, 5)” is a 5-period trailing moving
average, and “@movav(y(2), 5)” is a 5-period moving average centered around the
contemporaneous value.
• Because of its relative importance, a special centered moving average function
@movavc (p. 985) is provided. Note that if the number of periods provided is even,
the moving average produces a weighted moving average where the ends receive 0.5
weights.

Note that in contrast to the functions described in “Basic Statistics,” on page 692, computa-
tion of the rolling statistic values does not depend on the workfile sample so that sample
gaps will not change the underlying computations and values. The workfile sample only
comes into play when you assign the values of the function to a target series.

Basic Information
@mnas ................ Trailing moving missing observations (p. 981).
@mobs ................ Trailing moving non-missing observations (p. 982).

Rolling Statistics (Ignore NAs)


@mav .................. Trailing moving averages (ignore NAs) (p. 964).
@mavc................. Centered moving averages (ignore NAs) (p. 964).
@mcor ................. Trailing moving correlations (ignore NAs) (p. 968).
@mcov ................ Trailing moving population covariance (no d.f. adjustment; ignore
NAs) (p. 969).
@mcovp............... Trailing moving population covariance (no d.f. adjustment; ignore
NAs) (p. 970).
@mcovs ............... Trailing moving sample covariance (d.f. adjusted; ignore NAs)
(p. 971).
@minner.............. Trailing moving inner product of two series (ignore NAs) (p. 976).
@mkurt ............... Trailing moving kurtosis (ignore NAs) (p. 978).
@mmax ............... Trailing moving maximums (ignore NAs) (p. 979).
@mmedian .......... Trailing moving median (ignore NAs) (p. 980).
@mmin................ Trailing moving minimums (ignore NAs) (p. 980).
@mnas ................ Trailing moving missing observations (p. 981).
@mobs ................ Trailing moving non-missing observations (p. 982).
Function Summaries—699

@mskew...............Trailing moving skewness (ignore NAs) (p. 1001).


@mstdev ..............Trailing moving sample standard deviation (d.f. adjusted; ignore
NAs) (p. 1002).
@mstdevp.............Trailing moving population standard deviations (non-d.f. adjusted;
ignore NAs) (p. 1002).
@mstdevs .............Trailing moving sample standard deviations (d.f. adjusted; ignore
NAs) (p. 1003).
@msum ................Trailing moving sums (ignore NAs) (p. 1004).
@msumsq.............Trailing moving sums of squares (ignore NAs) (p. 1005).
@mvar .................Trailing moving population variances (non-d.f. adjusted; ignore
NAs) (p. 1005).
@mvarp................Trailing moving population variances (non-d.f. adjusted; ignore
NAs) (p. 1006).
@mvars ................Trailing moving population variances (d.f. adjusted; ignore NAs)
(p. 1007).

Rolling Statistics (Propagate NAs)


@movav ...............Trailing moving averages (propagate NAs) (p. 984).
@movavc..............Centered moving averages (propagate NAs) (p. 985).
@movcor ..............Trailing moving population correlations (propagate NAs) (p. 986).
@movcov .............Trailing moving population covariance (no d.f. adjustment; propa-
gate NAs) (p. 987).
@movcovp............Trailing moving population covariance (no d.f. adjustment; propa-
gate NAs) (p. 988).
@movcovs ............Trailing moving sample covariance (d.f. adjusted; propagate NAs)
(p. 989).
@movinner...........Trailing moving inner product of two series (propagate NAs)
(p. 990).
@movkurt ............Trailing moving kurtosis (propagate NAs) (p. 990).
@movmax ............Trailing moving maximums (propagate NAs) (p. 991).
@movmin.............Trailing moving minimums (propagate NAs) (p. 992).
@movskew ...........Trailing moving skewness (propagate NAs) (p. 993).
@movstdev...........Trailing moving sample standard deviations (d.f. adjusted; propa-
gate NAs) (p. 994).
@movstdevp .........Trailing moving population standard deviations (non-d.f. adjusted;
propagate NAs) (p. 994).
@movstdevs .........Trailing moving sample standard deviations (d.f. adjusted; propa-
gate NAs) (p. 995).
@movsum ............Trailing moving sums (propagate NAs) (p. 996).
@movsumsq .........Trailing moving sums of squares (propagate NAs) (p. 997).
700—Chapter 18.Function Summaries

@movvar ............. Trailing moving population variances (non d.f. adjusted; propagate
NAs) (p. 997).
@movvarp ........... Trailing moving population variances (non-d.f. adjusted; propagate
NAs) (p. 998).
@movvars............ Trailing moving sample variances (d.f. adjusted; propagate NAs)
(p. 999).

Cumulative Statistics
EViews provides functions for cumulative statistics computed using series data from the
beginning or end of a sample to the current observation.

The family of standard cumulatives includes familiar statistics such as means, medians,
standard deviations, and variances, to minimums and maximums, quantiles, numbers of
observations and missing values.
• The more commonly employed statistics that use data from the beginning of a sample
to the current observation may be termed forward cumulative statistics. These func-
tions are names of the form “@cum---”.
• The statistics using data from the current observation to the end of a sample are
referred to as backward cumulative statistics. These functions have names of the form
“@cumb---”.

Importantly, note that these forward and backward cumulative functions default to use all of
the data in the workfile. You may provide an alternate sample specification as a double
quoted last argument to the function. Observations that are not in the specified sample will
not contribute to the cumulative statistics.

In addition to the standard cumulative functions, EViews provides functions for specialized
computation of cumulative sums involving first differences of the series. There are three
types of functions:
• The first type, with names beginning with “@cumd”, computes cumulative differ-
ences of the series, conditional on being above, below, or at a threshold. We may
think of these partial sum processes as threshold cumulative differences.
• The second type, with names beginning with “@dcumd”, computes differences of the
threshold cumulative difference series.
• The third type, with functions that produce cumulative within a year, or within calen-
dar unit basis.

Forward Cumulatives
@cummax............ Cumulative maximums of a series (p. 793).
@cummean.......... Cumulative means of a series (p. 794).
@cummedian ....... Cumulative medians of a series (p. 794).
Function Summaries—701

@cummin.............Cumulative minimums of a series (p. 795).


@cumnas..............Cumulative number of missing observations of a series (p. 796).
@cumobs..............Cumulative number of (non-missing) observations of a series
(p. 797).
@cumprod............Cumulative products of a series or the elements of a matrix
(p. 797).
@cumquantile ......Cumulative quantiles of a series (p. 798).
@cumstdev ...........Cumulative standard deviations (d.f. corrected) of a series (p. 799).
@cumstdevp .........Cumulative standard deviations (non-d.f. corrected) of a series
(p. 800).
@cumstdevs .........Cumulative standard deviations (d.f. corrected) of a series (p. 801).
@cumsum ............Cumulative sums of a series or the elements of a matrix (p. 802).
@cumsumsq .........Cumulative sums-of-squares of a series (p. 803).
@cumvar..............Cumulative variances (non-d.f. corrected) of a series (p. 803).
@cumvarp ............Cumulative variances (non-d.f. corrected) of a series (p. 804).
@cumvars ............Cumulative variances (d.f. corrected) of a series (p. 805).

Backward Cumulatives
@cumbmax ..........Backward cumulative maximums of a series (p. 777).
@cumbmean.........Backward cumulative means of a series (p. 777).
@cumbmedian......Backward cumulative medians of a series (p. 778).
@cumbmin ...........Backward cumulative medians of a series (p. 779).
@cumbnas............Backward cumulative number of missing observations of a series
(p. 779).
@cumbobs............Backward cumulative number of (non-missing) observations of a
series (p. 780).
@cumbprod ..........Backward cumulative products of a series (p. 781).
@cumbquantile.....Backward cumulative quantiles of a series (p. 782).
@cumbstdev .........Backward cumulative standard deviations (d.f. corrected) of a
series (p. 783).
@cumbstdevp .......Backward cumulative standard deviations (non-d.f. corrected) of a
series (p. 784).
@cumbstdevs........Backward cumulative standard deviations (d.f. corrected) of a
series (p. 785).
@cumbsum ..........Backward cumulative sums of a series (p. 786).
@cumbsumsq .......Backward cumulative sums-of-squares of a series (p. 786).
@cumbvar ............Backward cumulative variances (non-d.f. corrected) of a series
(p. 787).
@cumbvarp ..........Backward cumulative variances (non-d.f. corrected) of a series
(p. 788).
702—Chapter 18.Function Summaries

@cumbvars .......... Backward cumulative variances (d.f. corrected) of a series (p. 789).

Threshold Cumulative Differences


@cumdn .............. Cumulative sum of negative (below threshold) changes in a series
(p. 790).
@cumdp .............. Cumulative sum of positive (above threshold) changes in a series
(p. 791).
@cumdz .............. Cumulative sum of zero (at threshold) changes in a series (p. 792).

Differences of Threshold Cumulative Differences


@dcumdn ............ Difference of cumulative sum of negative (below threshold)
changes in a series (p. 831).
@dcumdp ............ Difference of cumulative sum of positive (above threshold) changes
in a series (p. 832).
@dcumdz............. Difference of cumulative sum of zero (at threshold) changes in a
series (p. 833).

Calendar Cumulatives
@ytd.................... Within-year cumulative sum (year-to-date) (p. 1223).
@periodtodate ...... Within-period cumulative sum (period-to-date) (p. 1036).

By-Group Statistics
EViews offers a set of by-group statistics which compute statistics for sub-groups of data in
the workfile sample, and assign the relevant value to each observation. These by-group sta-
tistics may be used as part of any series expression to transform the raw series data into a
summary series

The functions take a series expression arg1 for which we wish to compute group statistics
and one or more series expressions arg2, defining the values over which we wish to com-
pute the statistics. In the leading case, you will provide a single series expression containing
a series or alpha whose values will define the category. More generally, you may provide
several series expressions separated by commas (arg2, arg3, ...) whose joint values define
the categories.

By default, EViews will use the workfile sample when computing the descriptive statistics.
You may provide an optional sample expression or named sample to adjust the computation.

There are two related functions of note,


@groupid(arg1[, arg2, arg3, arg4, ..., argn, smpl]])

returns an integer indexing the group ID for each observation of the series or alpha expres-
sions given by the arguments, and
@ngroups(arg1[, arg2, arg3, arg4, ..., argn, smpl])
Function Summaries—703

returns a scalar indicating the number of groups (distinct values) for the series or alpha
expressions defined by the arguments.

By-Group Statistics
@firstsby ..............First non-missing value in a series for each specified group (p. 887).
@kurtsby..............Kurtosis for each specified group (p. 937).
@lastsby ...............Last non-missing value in a series for each specified group (p. 941).
@maxsby..............Maximum values in a series for each specified group (p. 967).
@meansby ............Mean of observations in a series for each specified group (p. 972).
@mediansby .........Medians for a series for each specified group (p. 973).
@minsby ..............Minimum values in a series for each specified group (p. 977).
@nasby ................Number of missing observations in a series or alpha for each speci-
fied group (p. 1010).
@obsby ................Number of non-missing observations in a series or alpha, for each
specified group (p. 1016).
@quantilesby ........Empirical quantiles of a series for each specified group (p. 1058).
@skewsby ............Skewness for a series for each specified group (p. 1114).
@stdevpsby ..........Population standard deviations (d.f. corrected) for a series for each
specified group (p. 1119).
@stdevs ................Sample standard deviation (d.f. adjusted) (p. 1119).
@stdevsby ............Sample standard deviations (d.f. corrected) for a series for each
specified group (p. 1120).
@stdevssby...........Sample standard deviations (d.f. corrected) for a series for each
specified group (p. 1120).
@sumsby..............Sum of observations in a series for each specified group (p. 1136).
@sumsqsby ..........Sum of squared observations in a series for each specified group
(p. 1137).
@varpsby .............Population variances (non-d.f. corrected) of a series for each speci-
fied group (p. 1180).
@varsby ...............Sample variances (d.f. corrected) of a series for each specified
group (p. 1181).
@varssby..............Sample variances (d.f. corrected) of a series for each specified
group (p. 1182).

By-Row Statistics
EViews offers a set of statistics which compute summaries using data from all of the series
in each row of a group object, and assign that value to the corresponding observation. These
by-row statistics may be used as part of any series expression to extract a row summary
series from the data in a group.
704—Chapter 18.Function Summaries

Note that you may obtain the number of elements in the group rows using the @columns
(p. 762) function or using the data member groupname.@count.

Group Row Statistics


@rfirst ................. First non-missing value in rows of group (p. 1073).
@rifirst ................ Indices of first non-missing value in rows of group (p. 1075).
@rilast ................. Indices of last non-missing value in rows of group (p. 1076).
@rimax................ Indices of row maximums of group (p. 1077).
@rimin ................ Indices of row minimums of group (p. 1077).
@rlast .................. Last non-missing values in rows of group (p. 1081).
@rmax................. Row maximums of group (p. 1082).
@rmean ............... Row means of group (p. 1083).
@rmedian ............ Row medians of group (p. 1083).
@rmin ................. Row minimums of group (p. 1084).
@rnas .................. Number of missing observations in row of group (p. 1086).
@robs .................. Row numbers of non-missing observations in group (p. 1088).
@rprod ................ Row products in group (p. 1093).
@rquantile ........... Row quantiles in group (p. 1093).
@rstdev ............... Row sample (d.f. corrected) standard deviations of group (p. 1094).
@rstdevp.............. Row population (non d.f. corrected) standard deviations of group
(p. 1095).
@rstdevs .............. Row sample (d.f. corrected) standard deviations of group (p. 1096).
@rsum ................. Row sums of group (p. 1096).
@rsumsq.............. Row sums of squares of group (p. 1097).
@rvalcount .......... Number of matching values in rows of group (p. 1101).
@rvar .................. Row population (non d.f. corrected) variances of group (p. 1102).
@rvarp................. Row population (non d.f. corrected) variances of group (p. 1102).
@rvars ................. Row sample (d.f. corrected) standard deviations of group (p. 1103).

Matrix Functions
Matrix Utility
@capplyranks ...... Reorder the rows of the matrix using a vector of ranks (p. 733).
@columnextract ... Extract column from matrix (p. 762).
@columns............ Number of columns in matrix object or group (p. 762).
@convert ............. Converts series or group to a vector or matrix after removing NAs
(p. 764).
@eqna ................. Test for equality of data objects, treating NAs and null strings as
ordinary and not missing values (p. 873).
@explode ............. Square matrix from a sym matrix object (p. 880).
Function Summaries—705

@fill .....................Vector initialized from a list of values (p. 884).


@filledmatrix ........Matrix initialized with scalar value (p. 884).
@filledrowvector...Rowvector initialized with scalar value (p. 885).
@filledsym ...........Sym initialized with scalar value (p. 885).
@filledvector ........Vector initialized with scalar value (p. 886).
@getmaindiagonal Extract main diagonal from matrix (p. 895).
@grid ...................Vector containing equally spaced grid of values (p. 897).
@hcat ...................Vertically concatenate matrices (p. 899).
@identity..............Identity matrix (p. 913)
@implode .............Creates sym from lower triangle of square matrix (p. 919).
@implodeu ...........Creates sym from upper triangle of square matrix (p. 920).
@isna ...................Test for missing values (p. 927).
@lower.................Lowercase representation of a string, or lower triangular matrix of a
matrix (p. 951).
@makediagonal ....Create a matrix with vector placed on a diagonal (p. 961).
@mnrnd ...............Matrix of normal random numbers (p. 982).
@neqna ................Inequality test (NAs and blanks treated as values, not missing val-
ues) (p. 1010).
@ones ..................Matrix or vector of ones (p. 1018).
@permute.............Permutation of matrix (p. 1037).
@range .................Vector of sequential integers (p. 1063).
@ranks .................Ranking of values (p. 1064).
@rapplyranks .......Reorder the columns of a matrix using a vector of ranks (p. 1065).
@resample............Randomly draw from the rows of the matrix (p. 1071).
@rmvnorm ...........Multivariate normal random draws (p. 1085).
@rowextract .........Extract rowvector from matrix object (p. 1089).
@rows ..................Number of rows (p. 1090).
@rwish.................Wishart random draw (p. 1104).
@subextract..........Extract submatrix from matrix object (p. 1133).
@scale ..................Scale rows or columns of matrix (p. 1108).
@seq ....................Vector containing arithmetic sequence (p. 1110).
@seqm .................Vector containing geometric sequence (p. 1111).
@sfill....................Create a string vector from a list of strings (p. 1111).
@sort....................Sort elements of data object (p. 1116).
@unvec ................Unstack vector into a matrix (p. 1170).
@unvech ..............Unstack vector into lower triangle of sym (p. 1171).
@uniquevals.........Vector or svector of unique values of object (p. 1169).
@unitvector ..........Extracts column from an identity matrix (p. 1169).
706—Chapter 18.Function Summaries

@upper ................ Uppercase representation of a string; or upper triangular matrix of a


matrix (p. 1171).
@vcat .................. Vertically concatenate matrices (p. 1182).
@vec.................... Vectorize (stack columns of) matrix (p. 1183).
@vech.................. Vectorize (stack columns of) lower triangle of matrix (p. 1184).
@zeros................. Matrix or vector of zeros (p. 1225).

Matrix Algebra
@cholesky ........... Cholesky factor of matrix (p. 743).
@commute........... Commutation matrix (p. 763).
@cond ................. Condition number of square matrix or sym (p. 763).
@det .................... Determinant of matrix (p. 835).
@duplic ............... Duplication matrix (p. 849).
@duplicinv .......... Inverse duplication matrix (p. 850).
@eigenvalues ....... Vector of eigenvalues of a sym (p. 864).
@eigenvectors ...... Matrix whose columns contain the eigenvectors of a matrix
(p. 864).
@elimin ............... Elimination matrix (p. 867).
@inner................. Inner product (p. 922).
@inverse.............. Inverse of matrix (p. 926).
@issingular .......... Test matrix for singularity (p. 931).
@kronecker ......... Kronecker product (p. 935).
@lu...................... LU decomposition of a matrix (p. 954).
@norm ................ Norm of series or matrix object (p. 1012).
@outer................. Outer product of vectors or series (p. 1021).
@pinverse............ Moore-Penrose pseudo-inverse of matrix (p. 1038).
@qform................ Quadratic form (p. 1049).
@qr ..................... QR decomposition (p. 1055).
@rank.................. Rank of a matrix (p. 1063).
@rsweep .............. Reverse sweep operator (p. 1097).
@solvesystem....... Solve system of linear equations (p. 1115).
@svd ................... Singular value decomposition (economy) of matrix (p. 1137).
@svdfull .............. Singular value decomposition (full) of matrix (p. 1139).
@sweep ............... Sweep operator (p. 1140).
@trace ................. Computes the trace of a square matrix or sym (p. 1147).
@transpose .......... Transpose of a matrix object (p. 1147).
@unvec................ Unstack vector into a matrix (p. 1170).
@unvech.............. Unstack vector into lower triangle of sym (p. 1171).
@vec.................... Vectorize (stack columns of) matrix (p. 1183).
Function Summaries—707

@vech ..................Vectorize (stack columns of) lower triangle of matrix (p. 1184).

Matrix Statistics
@columns ............Number of columns in matrix object or group (p. 762).
@cor.....................Correlation of two vectors or series, or between the columns of a
matrix or series in a group (p. 766).
@cov ....................Covariance (non-d.f.corrected) of two vectors or series, or between
the columns of a matrix or series in a group (p. 767).
@covp ..................Covariance (non-d.f. corrected) of two vectors or series, or between
the columns of a matrix or series in a group (p. 767).
@covs...................Covariance (d.f. corrected) of two vectors or series, or between the
columns of a matrix or series in a group (p. 769).
@first ...................The first non-missing value in the vector or series (p. 886).
@gmean ...............Geometric mean (p. 896).
@hmean ...............Harmonic mean (p. 900).
@ifirst ..................Index of the first non-missing value in the vector or series (p. 914).
@ilast ...................Index of the last non-missing value in the vector or series (p. 915).
@imax..................Index of maximum value (p. 915).
@imaxes...............Indices of maximum value (multiple) (p. 917).
@imin ..................Index of minimum value (p. 918).
@imins .................Indices of minimum value (multiple) (p. 918).
@inner .................Inner product (p. 922).
@intercept ............Intercept from a trend regression (p. 925).
@kurt ...................Kurtosis (p. 936).
@last ....................The last non-missing value in the vector or series (p. 940).
@mae ...................Mean of absolute error (difference) between series (p. 959).
@mape .................Mean absolute percentage error (difference) between series
(p. 963).
@max...................Maximum value (p. 965).
@maxes................Maximum values (multiple) (p. 966).
@mean .................Arithmetic mean (p. 971).
@median ..............Median (p. 973).
@min ...................Minimum value (p. 975).
@mins..................Minimum values (multiple) (p. 976).
@mse ...................Mean of square error (difference) between series (p. 1000).
@nas ....................Number of missing observations (p. 1009).
@norm .................Norm of series or matrix object (p. 1012).
@obs ....................Number of observations (p. 1015).
@prod ..................Product (p. 1042).
708—Chapter 18.Function Summaries

@quantile ............ Empirical quantile (p. 1057).


@regress .............. Perform an OLS regression on the first column of a matrix versus
the remaining columns (p. 1069).
@rmse ................. Root of the mean of square error (difference) between series
(p. 1084).
@rows ................. Number of rows (p. 1090).
@skew................. Skewness (p. 1113).
@smape ............... Symmetric mean absolute percentage error (difference) between
series (p. 1114).
@stdev................. Sample standard deviation (d.f. adjusted) (p. 1117).
@stdevp ............... Population standard deviation (no d.f. adjustment) (p. 1118).
@stdevs ............... Sample standard deviation (d.f. adjusted) (p. 1119).
@stdize................ Standardized data (using sample standard deviation) (p. 1121).
@stdizep .............. Standardized data (using population standard deviation) (p. 1122).
@sum .................. Arithmetic sum (p. 1140).
@sumsq ............... Arithmetic sum of squares (p. 1136).
@theil .................. Theil inequality coefficient (difference) between series (p. 1145).
@trendcoef........... Trend coefficient from detrending regression (p. 1151).
@trmean .............. Trimmed mean (p. 1154).
@uniquevals ........ Vector or svector of unique values of object (p. 1169).
@valcount............ Number of matching values (p. 1178).
@var.................... Population variance (no d.f. adjustment) (p. 1179).
@varp .................. Population variance (no d.f. adjustment) (p. 1179).
@vars .................. Sample variance (d.f. adjusted) (p. 1181).

Matrix Column Statistics


@cfirst ................. First non-missing value in each column of a matrix (p. 740).
@cifirst ................ Index of the first non-missing value in each column of a matrix
(p. 744).
@cilast................. Index of the last non-missing value in each column of a matrix
(p. 745).
@cimax................ Index of the maximal value in each column of a matrix (p. 746).
@cimin ................ Index of the maximal value in each column of a matrix (p. 746).
@cintercept.......... Intercept from a trend regression performed on each column of a
matrix (p. 747).
@clast.................. Last non-missing value in each column of the matrix (p. 748).
@cmax................. Maximal value in each column of a matrix (p. 750).
@cmean............... Mean in each column of a matrix (p. 751).
@cmedian ............ Median of each column of a matrix (p. 751).
Function Summaries—709

@cmin..................Minimal value for each column of the matrix (p. 752).


@cnas...................Number of NA values in each column of a matrix (p. 752).
@cobs...................Number of non-NA values in each column of a matrix (p. 754).
@cprod.................Product of elements in each column of a matrix (p. 771).
@cquantile ...........Quantile of each column of a matrix (p. 771).
@cstdev ................Sample standard deviation (d.f. corrected) of each column of a
matrix (p. 772).
@cstdevp ..............Population standard deviation (non-d.f. corrected) of each column
of a matrix (p. 773).
@cstdevs ..............Sample standard deviation (non-d.f. corrected) of each column of a
matrix (p. 773).
@csum .................Sum of the values in each column of a matrix (p. 774).
@csumsq ..............Sum of the squared values in each column of a matrix (p. 774).
@ctrendcoef..........Slope from a trend regression on each column of a matrix (p. 775).
@ctrmean .............Trimmed mean of each column of a matrix (p. 776).
@cvar ...................Population variance of each column of a matrix (p. 807).
@cvarp .................Population variance of each column of a matrix (p. 807).
@cvars .................Sample variance of each column of a matrix (p. 808).

Matrix Element Functions


@ebtw ..................Element by element test for whether values are between two other
values (p. 860).
@ediv ...................Element by element division of two matrices (p. 861).
@eeq ....................Element by element equality comparison of two data objects
(p. 861).
@eeqna ................Element by element equality comparison of two data objects with
NAs treated as ordinary value for comparison (p. 862).
@ege ....................Element by element tests for whether the elements in the data
objects are greater than or equal to corresponding elements in
another data object (p. 863).
@egt.....................Element by element tests for whether the elements in the data
object strictly greater than corresponding elements in another data
object (p. 863).
@einv...................Element by element inverses of a matrix (p. 865).
@ele .....................Element by element tests for whether the elements in the data
object are less than or equal to corresponding elements in another
data object (p. 866).
@elt......................Element by element tests for whether the elements in the data
object are strictly less than corresponding elements in another data
object (p. 867).
710—Chapter 18.Function Summaries

@emax ................ Element by element maximums of two conformable data objects


(p. 868).
@emin ................. Element by element minimums of two conformable data objects
(p. 868).
@emult ................ Element by element multiplication of two matrix objects (p. 869).
@eneq ................. Element by element inequality comparison of two data objects
(p. 870).
@eneqna.............. Element by element inequality comparison of two data objects with
NAs treated as ordinary value for comparison (p. 871).
@epow ................ Raises each element in a matrix to a power (p. 873).
@erecode ............. Element by element recode of data objects (p. 876).

Matrix Transformation
Overall Transformation
@capplyranks ...... Reorder the rows of the matrix using a vector of ranks (p. 733).
@demean............. Compute deviations from the mean of the data object (p. 834).
@detrend ............. Compute deviations from the trend of the data object (p. 836).
@dupselem .......... Identifier for the observation within the set of duplicates (p. 851).
@dupsid .............. Identifier for the duplicates group for the observation (p. 852).
@dupsobs ............ Number of observations in the corresponding duplicates group
(p. 853).
@permute ............ Permutation of matrix (p. 1037).
@ranks ................ Ranking of values (p. 1064).
@rapplyranks....... Reorder the columns of a matrix using a vector of ranks (p. 1065).
@resample ........... Randomly draw from the rows of the matrix (p. 1071).
@transpose .......... Transpose of a matrix object (p. 1147).

Transform By-Column
@colcumprod....... Cumulative products for each column of a matrix (p. 754).
@colcumsum ....... Cumulative sums for each column of a matrix (p. 755).
@coldemean ........ Demean each column of a matrix (p. 756).
@coldetrend......... Detrend each column of a matrix (p. 757).
@colpctiles........... Percentile values for each column of a matrix (p. 758).
@colranks............ Ranks of each column of the matrix (p. 758).
@colsort............... Sort each column of the matrix (p. 759).
@colstdize ........... Standardize each column using the sample (d.f. corrected) standard
deviation (p. 760).
@colstdizep.......... Standardize each column using the population (non-d.f. corrected)
standard deviation (p. 761).

Transform By-Row
Function Summaries—711

@rowranks ...........Matrix where each row contains ranks of the column values
(p. 1090).
@rowsort..............Matrix where each row contains sorted columns (p. 1091).

Support Functions
@addinspath.........EViews add-ins directory path (p. 714).
@attrnames ..........Attribute names in workfile page (p. 718).
@attrvals ..............Attribute values in workfile page (p. 719).
@dbname .............String containing the default database name (p. 829).
@equaloption .......Equals-to option value provided in the exec or run commands
(p. 875).
@env....................Windows environment variable string (p. 872).
@errorcount .........Number of errors encountered running a program (p. 878).
@evpath ...............Directory path of the EViews executable (p. 877).
@fileexist..............Check for existence of a file on disk (p. 883).
@folderexist..........Check for existence of a folder on disk (p. 888).
@getnextname ......String containing next available name in the workfile (p. 895).
@getthistype .........Object type of active object (_this) (p. 896).
@hasoption...........Indicator for whether option is provided in the exec or run com-
mand (p. 899).
@isobject ..............Does object exist in active workfile page (p. 929).
@isvalidgroup.......Does the string represent a valid EViews group or auto-series
(p. 931).
@isvalidname .......Indicator for whether string represents a valid name for an EViews
object (p. 932).
@lasterrnum .........Last error number generated by a previously issued command
(p. 941).
@lasterrstr ............Last error message generated by a previously issued command
(p. 942).
@linepath .............Location of the program file currently being executed (p. 944).
@loadprgini ..........Variable name value in an “.ini” file (p. 945).
@makevalidname .Make string into a valid EViews name (p. 962).
@maxerrcount ......Maximum number of errors in a program before halting execution
(p. 966).
@option................Option string provided in the exec or run command (p. 1019).
@runpath .............Location of the program currently being executed (p. 1101).
@tablenames ........Tables names in a foreign file (p. 1143).
@temppath ...........Directory path for EViews temporary files (p. 1145).
@toc.....................Elapsed time (since timer reset) in seconds (p. 1146).
@uidialog .............Display a dialog with multiple controls (p. 1159).
712—Chapter 18.Function Summaries

@uiedit ................ Display a dialog with an edit control (p. 1162).


@uifiledlg ............ Display a file open and save dialog (p. 1163).
@uilist ................. Display a dialog with a listbox control (p. 1164).
@uimlist .............. Display a dialog with a multiple-select listbox control (p. 1165).
@uiprompt........... Display a prompt dialog (p. 1166).
@uiradio .............. Display a dialog with radio buttons (p. 1168).
@vernum ............. EViews version number (p. 1184).
@verstr ................ EViews product name string (p. 1184).
@wdir.................. List of all files in a directory (p. 1190).
@wfattrnames ...... String containing a list of attribute names in the workfile (p. 1194).
@wfattrvals.......... String containing a list of attribute values in the workfile (p. 1195).
@wfpath .............. String containing path of current workfile (p. 1198).
@wlookup ........... String list formed from objects in a workfile or database matching a
pattern (p. 1204).
@wquery ............. String containing list of object attributes for objects matching a
database query (p. 1209).
@xgetstr .............. String value from the external application.(p. 1219).
@xgetnum ........... Scalar numeric value from the external application.(p. 1219).
@xputnames ........ List of objects created in foreign application using XPUT (p. 1220).
@xtype ................ Type of active external connection (p. 1220).
@xverstr .............. External application version number as a string (p. 1221).
@xvernum ........... External application version number as a number (p. 1221).
abs—713

Function Reference: A
@abs ....................Absolute value (p. 713).
abs........................Absolute value (p. 713).
@acos...................Arc cosine (in radians) (p. 714).
@addinspath.........EViews add-ins directory path (p. 714).
@addquotes ..........Enclose string in quotation marks (p. 715).
@after ..................Indicators for whether observation postdates a date (p. 716).
@asc.....................ASCII value of character (p. 717).
@asin ...................Arc sin (in radians) (p. 717).
@atan...................Arc tangent (in radians) (p. 718).
@attrnames ..........Attribute names in workfile page (p. 718).
@attrvals ..............Attribute values in workfile page (p. 719).

@abs Element Functions

Absolute value.
Syntax: @abs(x)
x: number
Return: number

Examples
= @abs(-3)

returns 3.

Cross-references
See also abs (p. 713).

abs Element Functions

Absolute value.
Syntax: abs(x)
x: number
Return: number

Examples
= abs(-3)

returns 3.
714—Function Reference: A

Cross-references
See also @abs (p. 713).

@acos Element Functions

Arc cosine.

Compute the arc cosine (in radians) of x.


Syntax: @acos(x)
x: number
Return: number

Examples
= @acos(1)

returns 0.

Cross-references
See also @asin (p. 717), @atan (p. 718), @cos (p. 766), @sin (p. 1112), and @tan (p. 1144).

@addinspath Support Functions

Path of the EViews add-ins directory.


Syntax: @addinspath
Return: string

Returns a string containing the EViews add-ins directory path.

Examples
If your currently add-ins path is “d:\eviews\add_ins”, then
%y = @addinspath

assigns a string of the form “D:\EVIEWS\ADD_INS”.

Cross-references
See also @evpath (p. 878) and @temppath (p. 1145).
@addquotes—715

@addquotes Element Functions | String Functions

Enclose string in quotation marks.


Syntax: @addquotes(str)
str: string, alpha, svector
Return: string, alpha, svector

Returns the contents of the string in str with double-quotation marks added to both the left
and the right.

Examples
Define the string object
string s1 = "Chicken Marsala"

so that S1 contains the unquoted string “Chicken Marsala”.

Then the commands


string sq1 = """Chicken Marsala"""
string sq2 = @addquotes(s1)

create SQ1 and SQ2 which both contain the quoted string “"Chicken Marsala"”. The first
command uses the double-quote escape sequence “""” to add the double-quotes. The latter
command uses the function.

If ALPHSER is an alpha series, the command


alpha a1 = @addquotes(ALPHSER)

fills A1 with double-quoted values of ALPHSER for each observation in the workfile sample.

If AVEC is an svector, the commands


svector as1 = @addquotes(avec)
svector as2 = @addquotes(avec.@rows(@range(1, 3))

create svectors AS1 and AS2, where AS1 contains double-quoted values of AVEC, and AS2
contains double-quoted values of the first three rows of AVEC.

Cross-references
See also @stripquotes (p. 1131).
716—Function Reference: A

@after Workfile Functions

Indicator series for whether an observation postdates a given date.


Syntax: @after(d)
d: string, alpha
Return: series

Returns a series containing indicators for whether each observation postdates the corre-
sponding date d.
• For dates d that are of equal or lower frequency than the observation, the results are
(0, 1) indicators of whether the observation is on or after the beginning of d.
• For dates d that are of higher frequency than the observation, the (0, n) results reflect
the fraction of the observation on or after the beginning of d.

Examples
Suppose that we have a quarterly workfile with data from 2020q1 to 2022q4 that we create
with the command:
workfile q 2020 2022

The command
series after_y = @after("2021")

uses a lower-frequency “yearly” date to creates the series AFTER_Y containing the value 1
from 2021q1 through the end of the workfile, and 0 elsewhere.

Using a “quarterly” date,


series after_q = @after("2021q3")

creates the series AFTER_Q containing the value 1 beginning in 2021q3 through the end of
the workfile, and 0 elsewhere.

The command using a higher frequency “monthly” date


series after_m = @after("2021m5")

generates the series AFTER_M containing the value 0 from 2020q1 through 2021q1, a frac-
tional value for 2021q2, and the value 1 from 2021q3 through the end of the data.

For the fractional 2021q2 value, there are 61 days in 2021-May and 2021-June that are after
the beginning of the “2021m5” date and 91 days in the full quarter, so the fractional value for
2021q2 is 61/91 = 0.67033.
@asin—717

Cross-references
See also @before (p. 721) and @during (p. 854).

@asc Element Functions | String Functions

String to ASCII value.


Syntax: @asc(str)
str: string
Return: string

Returns the integer ASCII value for the first character in the string str.

Examples
scalar s1 = @asc("C")
scalar s2 = @asc("c")

returns the scalars S1=67 and S2=99.

Cross-references
See also @chr (p. 744).

@asin Element Functions

Arc sine.

Compute the arc sine (in radians) of x.


Syntax: @asin(x)
x: number
Return: number

Examples
= @asin(1)

returns 1.57079... (radians).

Cross-references
See also @acos (p. 714), @atan (p. 718), @cos (p. 766), @sin (p. 1112), and @tan (p. 1144).
718—Function Reference: A

@atan Element Functions

Arc tangent.

Compute the arc tangent (in radians) of x.


Syntax: @atan(x)
x: number
Return: number

Examples
= @atan(1)

returns 0.78539... (radians).

Cross-references
See also @acos (p. 714), @asin (p. 717), @cos (p. 766), @sin (p. 1112), and @tan (p. 1144).

@attrnames Support Functions

Attribute names in workfile page.


Syntax: @attrnames(attr[, obj, opt])
attr: string
obj: (optional) string
opt: (optional) integer
Return: string

Returns a string list of all attribute names in the active workfile page that match the attr pat-
tern and, optionally, whose object names also match the obj name pattern.
• The attr is a space delimited list of attribute value patterns. The list may be made up
of any number of names, or “?” (indicates any single character) or “*” (indicates any
number of characters) patterns.
• The obj list may be made up of any number of names, or “?” (indicates any single
character) or “*” (indicates any number of characters) patterns separated by spaces.
• The opt is an integer value indicating how a “*” or “?” in the attr should be treated
when matching. Use “0” to treat the characters as wildcards, and “1” to treat the char-
acters as literals. The default is “0”.

Matches are not case-sensitive.


@attrvals—719

Examples
If a workfile contains three objects named “GDP”, “UNEMP”, and “INFLATION”
@attrnames("M*")

returns the list of attributes of GDP, UNEMP, INFLATION that begin with “M”. Alternately,
@attrnames("M* S*", "GDP")

returns the list of attributes for the object GDP that begin with “M” and “S”.

If GDP had an attribute named “*Note” and UNEMP had an attribute named “footnote” the
command
@attrnames("*NOTE", "*")

will return “*Note footnote” since by default, the “*” in “*Note” is treated as a wildcard.
However, the command
@attrnames("*NOTE", "*", 1)

will return “*Note”, since the “*” in “*Note” is treated as a literal.

Cross-references
See also @attrvals (p. 719), @wfattrnames (p. 1194), and @wfattrvals (p. 1195).

@attrvals Support Functions

Attribute values in workfile page.


Syntax: @attrvals(attr[, obj, opt])
attr: string
obj: (optional) string
opt: (optional) integer
Return: string

Returns a string list of all attribute values in the active workfile page that match the attr pat-
tern and, optionally, whose object names also match the obj name pattern.
• The attr is a space delimited list of attribute value patterns. The list may be made up
of any number of names, or “?” (indicates any single character) or “*” (indicates any
number of characters) patterns.
• The obj list may be made up of any number of names, or “?” (indicates any single
character) or “*” (indicates any number of characters) patterns separated by spaces.
720—Function Reference: A

• The opt is an integer value indicating how a “*” or “?” in the attr should be treated
when matching. Use “0” to treat the characters as wildcards, and “1” to treat the char-
acters as literals.

Matches are not case-sensitive.

Examples
If a workfile contains three objects named “GDP”, “UNEMP”, and “INFLATION”, each
object contained a “month” attribute where the GDP “month” values was “Jan”, the
UNEMP value was “Feb”, and the INFLATION value was “Mar”, then
@attrvals("M*")

return the string list “Mar”. All attributes values for all objects in the workfile that begin
with “M” are included. Alternatively,
@attrvals("M* D*", "GDP")

returns the list of attribute values for the object GDP that begin with “M” and “S”.

If a fourth object INTEREST has an attribute value “*Mar” for “month,” the command
@attrvals("*mar", "*")

will return “*mar mar”, since by default, the “*” in “*mar” is treated as a wildcard and the
value “Mar” from INFLATION and value “*Mar” from INTEREST match.

However, the command


@attrvals("*mar", "*", 1)

will only return “*mar”, since the “*” in “*Mar” is treated as a literal for purposes of match-
ing, and only “*Mar” from INTEREST matches.

Cross-references
See also @attrnames (p. 718), @wfattrnames (p. 1194), and @wfattrvals (p. 1195).
@before—721

Function Reference: B
@before ................Indicators for whether observation precedes a date (p. 721).
@beta ...................Beta integral (Euler integral of the second kind) (p. 722).
@betainc ..............Incomplete beta integral (p. 723).
@betaincder..........Derivative of the incomplete beta integral (p. 723).
@betaincinv..........Inverse of the incomplete beta integral (p. 724).
@betalog ..............Natural logarithm of the beta integral (p. 725).
@between.............Dummy variable for value within range of values (p. 725).
@binom................Binomial coefficient (p. 726).
@binomlog ...........Natural logarithm of the binomial coefficient (p. 726).
@bounds ..............Bounded values (p. 727).
@bridge................Copy of a series using the current or preceding non-missing value
(p. 727).

@before Workfile Functions

Indicator for whether an observation precedes a given date.


Syntax: @before(d)
d: string, alpha
Return: series

Returns a series containing indicators for whether each observation precedes the beginning
of the specified date d.
• For dates d that are of equal or lower frequency than the observation, the results are
(0, 1) indicators of whether the observation precedes the beginning of d.
• For dates d that are of higher frequency than the observation, the (0, n) results reflect
the fraction of the observation before the beginning of d.

Examples
Suppose that we have a quarterly workfile with data from 2020q1 to 2022q4 that we create
with the command:
workfile q 2020 2022

The command
series before_y = @before("2022")

uses a lower-frequency “yearly” date to creates the series BEFORE_Y containing the value 1
from 2020q1 through 2021q4, and the value 0 elsewhere.

Using a “quarterly” date,


722—Function Reference: B

series before_q = @before("2022q3")

creates the series BEFORE_Q containing the value 1 from 2020q1 through 2022q2 and the
value 0 elsewhere.

The command using a higher frequency “monthly” date


series before_m = @before("2022m5")

generates the series BEFORE_M containing the value 1 from 2020q1 through 2022q1, a frac-
tional value for 2022q2 which contains 2022m5, and the value 0 beginning in 2022q3
through the end of the data.

For the fractional 2022q2 value, there are 30 days in 2022-April that precede the beginning of
the “2022m5” date. There are 91 days in the full quarter, so the fractional before value for
2022q2 is 30/91 = 0.32967.

Cross-references
See also @before (p. 721) and @during (p. 854).

@beta Element Functions

Beta integral (Euler integral of the second kind).


Syntax: @beta(a, b)
a: number
b number
Return: number

Compute the value of the beta integral for elements of a and b:


1 a–1 b–1 G  a G  b 
B  a, b   0 t 1 – t dt  ------------------------
Ga  b
for a, b  0 .

Examples
= @beta(1,5)

returns 0.2 (same as 1/5).

Cross-references
See also @betainc (p. 723), @betaincder (p. 723), @betaincinv (p. 724), and @betalog
(p. 725).
@betaincder—723

@betainc Element Functions

Incomplete beta integral.


Syntax: @betainc(x, a, b)
x: number
a: number
b number
Return: number

Compute the value of the incomplete beta integral for elements of x, a and b:
1 x a–1 b–1
IB  x, a, b   ------------------  t 1 – t dt
B  a, b  0
for 0  x  1 and a, b  0 .

Examples
= @betainc(0.5,3,1)

returns 0.125 (same as 0.5 raised to the power of 3).

Cross-references
See also @beta (p. 722), @betaincder (p. 723), @betaincinv (p. 724), and @betalog
(p. 725).

@betaincder Element Functions

Derivative of the incomplete beta integral.


Syntax: @betaincder(x, a, b, c)
x: number
a: number
b number
c integer
Return: number

Given the incomplete beta integral for elements of x, a and b:


1 x a–1 b–1
IB  x, a, b   ------------------  t 1 – t dt
B  a, b  0
for 0  x  1 and a, b  0 , compute the derivative given by c where c is an integer from 1
to 9 indicating the desired derivative,
724—Function Reference: B

IB IB IB


---------- ---------- ----------
x a b
1 2 3 2 2
IB  IB  IB
-----------
2

4 5 6  - ------------- ------------
2
x xa xb
7 8 9 2 2 2
 IB  IB  IB
------------ ------------- ------------
2 2
a ab b

If c is not an integer, the integer floor c will be used.

Examples
= @betaincder(0.5,2,2,1)

returns 1.5.

Cross-references
See also @beta (p. 722), @betainc (p. 723), @betaincinv (p. 724), and @betalog (p. 725).

@betaincinv Element Functions

Inverse of the incomplete beta integral.


Syntax: @betaincinv(x, a, b, p)
p: number
a: number
b number
Return: number

Returns the x satisfying the incomplete beta integral for elements of p, a and b:
1 x a–1 b–1
p  ------------------  t 1 – t dt
B  a, b  0
for 0  p  1 and a, b  0 .

Examples
= @betaincinv(0.5,2,2)

returns 0.5.

Cross-references
See also @beta (p. 722), @betainc (p. 723), @betaincder (p. 723), and @betalog (p. 725).
@between—725

@betalog Element Functions

Natural logarithm of the beta integral.


Syntax: @betalog(a, b)
a: number
b number
Return: number

Compute the value of the beta integral for elements of a and b:

log B  a, b   log   t dt


1 a–1 b–1
1 – t
 0 
 log G  a   log G  b  – log G  a  b 
for a, b  0 .

Examples
= @betalog(2,1)

returns -0.69314....

Cross-references
See also @beta (p. 722), @betainc (p. 723), @betaincder (p. 723), and @betaincinv
(p. 724).

@between Workfile Functions

Dummy variable for observation value within range of values.


Syntax: @between(x, v1, v2)
x: number or string
v1: number or string
v2: number or string
Return: number
where v1 and v2 correspond to the low and high values of the range.

Returns a dummy variable series equal to 1 for observations where x is greater than or equal to
v1 and less than or equal to v2, and 0 otherwise.

Examples
series d1 = @between(x, 10, 100)
726—Function Reference: B

creates a dummy variable that takes the value 1 where the value of X is in the range defined
by the values 10 and 100.
series d2 = @between(x, lowvals, highvals)

creates a dummy variable that takes the value 1 where the value of X is in the range defined
by the series LOWVALS and HIGHVALS.

Cross-references
See also @inlist (p. 921), and @between (p. 725).

@binom Element Functions

Binomial coefficient.
Syntax: @binom(n, x)
a: number
b number
Return: integer

Compute the value of the beta integral for elements of a and b:


 n   ------------------------
n!
-
x  x!  n – x !
for integers 0  x  n and n  0 . If n or x are not integers, the integer floors n and x
will be used.

Examples
= @binom(4,2)

returns 6.

Cross-references
See also @binomlog (p. 726).

@binomlog Element Functions

Natural logarithm of the binomial coefficient.


Syntax: @binomlog(n, x)
n: integer
x: integer
Return: number
@bridge—727

Compute the value of the beta integral for elements of a and b:


n
log    log  n!  – log  x!  – log   n – x ! 
x 

for integers n  0 and 0  x  n .

If n or x are not integers, the integer floors n and x will be used.

Examples
= @binomlog(2,1)

returns 0.69314....

Cross-references
See also @binom (p. 726).

@bounds Element Functions

Bounded values.
Syntax: @bounds(x, y, z)
x: number
y: number
z: number
Return: number

Returns x if y  x  z , or the boundary values y if x  y or z if x  z .

Examples
= @bounds(x, 0, 1)

returns the value of x if x is in the unit interval, 0 if x is negative, and 1 if x is greater than 1.

@bridge Series Utility

Copy of a series using current or preceding non-missing value.


Syntax: @bridge(x)
x: series
Return: series
Returns a copy of series x with NAs replaced by the nearest preceding non-NA value.

This function is panel aware.


728—Function Reference: B

Examples
series x = @recode(@rnd < 0.5, na, @nrnd)
show @bridge(x)

The first line create a series x of NAs and IID standard normal variates. The second line
shows x with @bridge applied. Note that NAs that appear at the beginning of the series do
not get replaced.

Cross-references
See also @nan (p. 1009).
Function Reference: C—729

Function Reference: C
@cagr ...................Compound annual growth rate of series (in decimal fraction)
(p. 732).
@capplyranks .......Reorder the rows of the matrix using a vector of ranks (p. 733).
@cbeta .................Beta cumulative distribution function (p. 734).
@cbinom ..............Binomial cumulative probability function (p. 735).
@cbvnorm ............Bivariate normal cumulative distribution function (p. 735).
@cchisq................Chi-square cumulative distribution function (p. 736).
@ceil ....................Smallest number greater than or equal to (with optional precision)
(p. 737).
@cellid .................Within cross-section identifier series for panel workfile observation
(p. 737).
@cexp ..................Exponential cumulative distribution function (p. 738).
@cextreme............Extreme value (Type I-minimum) cumulative distribution function
(p. 739).
@cfdist .................F-distribution cumulative distribution function (p. 739).
@cfirst..................First non-missing value in each column of a matrix (p. 740).
@cgamma.............Gamma cumulative distribution function (p. 741).
@cged ..................Generalized error cumulative distribution function (p. 742).
@chisq .................Upper tail of the Chi-square cumulative distribution function
(p. 742).
@cholesky ............Cholesky factor of matrix (p. 743).
@chr ....................ASCII value to string character (p. 744).
@cifirst.................Index of the first non-missing value in each column of a matrix
(p. 744).
@cilast .................Index of the last non-missing value in each column of a matrix
(p. 745).
@cimax ................Index of the maximal value in each column of a matrix (p. 746).
@cimin.................Index of the maximal value in each column of a matrix (p. 746).
@cintercept...........Intercept from a trend regression performed on each column of a
matrix (p. 747).
@claplace .............Laplace cumulative distribution function (p. 747).
@clast ..................Last non-missing value in each column of the matrix (p. 748).
@clogistic .............Logistic cumulative distribution function (p. 748).
@cloglog...............Complimentary log-log function (p. 749).
@clognorm ...........Log normal cumulative distribution function (p. 749).
@cmax .................Maximal value in each column of a matrix (p. 750).
@cmean ...............Mean in each column of a matrix (p. 751).
730—Function Reference: C

@cmedian ............ Median of each column of a matrix (p. 751).


@cmin ................. Minimal value for each column of the matrix (p. 752).
@cnas .................. Number of NA values in each column of a matrix (p. 752).
@cnegbin............. Negative binomial cumulative probability function (p. 753).
@cnorm ............... Standard normal cumulative distribution function (p. 753).
@cobs .................. Number of non-NA values in each column of a matrix (p. 754).
@colcumprod....... Cumulative products for each column of a matrix (p. 754).
@colcumsum ....... Cumulative sums for each column of a matrix (p. 755).
@coldemean ........ Demean each column of a matrix (p. 756).
@coldetrend......... Detrend each column of a matrix (p. 757).
@colpctiles........... Percentile values for each column of a matrix (p. 758).
@colranks............ Ranks of each column of the matrix (p. 758).
@colsort............... Sort each column of the matrix (p. 759).
@colstdize ........... Standardize each column using the sample (d.f. corrected) standard
deviation (p. 760).
@colstdizep.......... Standardize each column using the population (non-d.f. corrected)
standard deviation (p. 761).
@columnextract ... Extract column from matrix (p. 762).
@columns............ Number of columns in matrix object or group (p. 762).
@commute........... Commutation matrix (p. 763).
@cond ................. Condition number of square matrix or sym (p. 763).
@convert ............. Converts series or group to a vector or matrix after removing NAs
(p. 764).
@cor .................... Correlation of two vectors or series, or between the columns of a
matrix or series in a group (p. 766).
@cos.................... Cosine of argument specified in radians (p. 766).
@cov ................... Covariance (non-d.f.corrected) of two vectors or series, or between
the columns of a matrix or series in a group (p. 767).
@covp ................. Covariance (non-d.f. corrected) of two vectors or series, or between
the columns of a matrix or series in a group (p. 767).
@covs .................. Covariance (d.f. corrected) of two vectors or series, or between the
columns of a matrix or series in a group (p. 769).
@cpareto.............. Pareto cumulative distribution function (p. 769).
@cpoisson............ Poisson cumulative probability function (p. 770).
@cprod ................ Product of elements in each column of a matrix (p. 771).
@cquantile........... Quantile of each column of a matrix (p. 771).
@crossid .............. Cross-section identifier series for panel workfile observation
(p. 772).
Function Reference: C—731

@cstdev ................Sample standard deviation (d.f. corrected) of each column of a


matrix (p. 772).
@cstdevp ..............Population standard deviation (non-d.f. corrected) of each column
of a matrix (p. 773).
@cstdevs ..............Sample standard deviation (non-d.f. corrected) of each column of a
matrix (p. 773).
@csum .................Sum of the values in each column of a matrix (p. 774).
@csumsq ..............Sum of the squared values in each column of a matrix (p. 774).
@ctdist .................Student’s t cumulative distribution function (p. 775).
@ctrendcoef..........Slope from a trend regression on each column of a matrix (p. 775).
@ctrmean .............Trimmed mean of each column of a matrix (p. 776).
@cumbmax ..........Backward cumulative maximums of a series (p. 777).
@cumbmean.........Backward cumulative means of a series (p. 777).
@cumbmedian......Backward cumulative medians of a series (p. 778).
@cumbmin ...........Backward cumulative medians of a series (p. 779).
@cumbnas............Backward cumulative number of missing observations of a series
(p. 779).
@cumbobs............Backward cumulative number of (non-missing) observations of a
series (p. 780).
@cumbprod ..........Backward cumulative products of a series (p. 781).
@cumbquantile.....Backward cumulative quantiles of a series (p. 782).
@cumbstdev .........Backward cumulative standard deviations (d.f. corrected) of a
series (p. 783).
@cumbstdevp .......Backward cumulative standard deviations (non-d.f. corrected) of a
series (p. 784).
@cumbstdevs........Backward cumulative standard deviations (d.f. corrected) of a
series (p. 785).
@cumbsum ..........Backward cumulative sums of a series (p. 786).
@cumbsumsq .......Backward cumulative sums-of-squares of a series (p. 786).
@cumbvar ............Backward cumulative variances (non-d.f. corrected) of a series
(p. 787).
@cumbvarp ..........Backward cumulative variances (non-d.f. corrected) of a series
(p. 788).
@cumbvars...........Backward cumulative variances (d.f. corrected) of a series (p. 789).
@cumdn ...............Cumulative sum of negative (below threshold) changes in a series
(p. 790).
@cumdp ...............Cumulative sum of positive (above threshold) changes in a series
(p. 791).
@cumdz ...............Cumulative sum of zero (at threshold) changes in a series (p. 792).
732—Function Reference: C

@cummax............ Cumulative maximums of a series (p. 793).


@cummean.......... Cumulative means of a series (p. 794).
@cummedian ....... Cumulative medians of a series (p. 794).
@cummin ............ Cumulative minimums of a series (p. 795).
@cumnas ............. Cumulative number of missing observations of a series (p. 796).
@cumobs ............. Cumulative number of (non-missing) observations of a series
(p. 797).
@cumprod ........... Cumulative products of a series or the elements of a matrix
(p. 797).
@cumquantile...... Cumulative quantiles of a series (p. 798).
@cumstdev .......... Cumulative standard deviations (d.f. corrected) of a series (p. 799).
@cumstdevp ........ Cumulative standard deviations (non-d.f. corrected) of a series
(p. 800).
@cumstdevs......... Cumulative standard deviations (d.f. corrected) of a series (p. 801).
@cumsum............ Cumulative sums of a series or the elements of a matrix (p. 802).
@cumsumsq ........ Cumulative sums-of-squares of a series (p. 803).
@cumvar ............. Cumulative variances (non-d.f. corrected) of a series (p. 803).
@cumvarp ........... Cumulative variances (non-d.f. corrected) of a series (p. 804).
@cumvars............ Cumulative variances (d.f. corrected) of a series (p. 805).
@cunif ................. Uniform cumulative distribution function (p. 806).
@cvar .................. Population variance of each column of a matrix (p. 807).
@cvarp ................ Population variance of each column of a matrix (p. 807).
@cvars................. Sample variance of each column of a matrix (p. 808).
@cweib................ Weibull cumulative distribution function (p. 808).

@cagr Series Utility

Compound annual growth rate (in decimal fraction).


Syntax: @cagr(x, n)
x: series
n: integer
Return: series

Returns the n-th root of the total return of x over n periods:


--1-
xt  n
y t   ----------
- –1
 xt – n 
@capplyranks—733

This function is panel aware.

Examples
If x is a series of quarterly profits, then
show @cagr(x, 1)

returns a linked series containing annualized profit growth rates in decimal fraction.

Cross-references
See also @pccagr (p. 1032).

@capplyranks Matrix Utility

Reorder the rows of a matrix using a vector of ranks.


Syntax: @capplyranks(m, v[, n])
m: matrix, vector
v: vector
n: (optional) integer
Return: matrix, vector

Apply (a column of) row ranks in the vector v to reorder the rows of a matrix m using the
ranks.
• v should contain unique integers from 1 to the number of rows of m.
• If the optional argument n is specified, only the elements in column n will be reor-
dered.

Examples
matrix m1 = @mnrnd(10, 4)
vector v1 = @ranks(m1.@col(4), "a", "i")
matrix m2 = @capplyranks(m1, v1)

reorders the rows of the matrix M1 using the ranks in V1. Note that you may use the @ranks
function to obtain the ranks of a vector, but must obtain unique integer ranking for data
with ties through use of the “i” or “r” option in @ranks.
matrix m3 = @capplyranks(m1, v1, 3)

reorders only the elements of column 3 of M1.

Cross-references
See also @sort (p. 1116), @colsort (p. 759), and @rowsort (p. 1091).
734—Function Reference: C

See also @ranks (p. 1064), @colranks (p. 758).

See also @rapplyranks (p. 1065).

@cbeta Element Functions

Beta distribution cumulative distribution.


Syntax: @cbeta(x, a, b[, u])
x: number
a: number, a  0
b: number, b  0
u: (optional) number
Return: number

Computes the cumulative distribution function

 0 x0
 x
F  x, a, b    0 f  s, a, b  ds 0x1

 1 x1

where
a–1 b–1
s 1 – s
f  s, a, b   --------------------------------------
B  a, b 
and B is the beta function
1
a–1 b–1 G  a G  b 
B  a, b   t 1 – t dt  ------------------------
Ga  b
0

If the optional argument u is non-zero, return the upper-tail value: 1 – F  x, a, b  .

Examples
= @cbeta(0.5, 1, 2)

returns 0.75.

Cross-references
See also @dbeta (p. 828), @qbeta (p. 1045), and @rbeta (p. 1067).
@cbvnorm—735

@cbinom Element Functions

Binomial distribution cumulative probability.


Syntax: @cbinom(x, n, p)
x: number
n: integer, n  0
p: number, 0  p  1
Return: number

Computes the cumulative probability function

 x n j
F  x, a, b       p  1 – p 
n–j
0xn
 j
j  0

and

0 x0
F  x, a, b   
1 xn

where x is the integer floor of x .

Examples
= @cbinom(1, 5, 0.5)

returns 0.1875.

Cross-references
See also @dbinom (p. 828), @qbinom (p. 1046), and @rbinom (p. 1067).

@cbvnorm Element Functions

Bivariate normal cumulative probability.


Syntax: @cbvnorm(x, y, r)
x: number
y: number
p: number, 0  r  1
Return: number

Computes the cumulative distribution function for a bivariate normal with 0 mean, unit
variances, and correlation r:
736—Function Reference: C

x y
F  x, y r     f  s, t, r  dt ds
0 0

where

1  1 2 2 
f  s, t r   -------------------------- exp  – ----------------------  x – 2rxy  y  
2
2p 1 – r
2  21 – r  

Examples
= @cbvnorm(0, 0, 0.5)

returns 0.33333....

Cross-references
See also @dbvnorm (p. 829).

@cchisq Element Functions

Chi-square cumulative distribution.


Syntax: @cchisq(x, v[, u])
x: number
v: number, v  0
u: (optional) number
Return: number

Computes the cumulative distribution function

 0
 x0
F  x, v    x
 0 f  s v  ds x0

where
1 v2–1
f  s v   ------------------------------ s exp  – s  2 
v2
2 Gv  2
If the optional argument u is non-zero, return the upper-tail value: 1 – F  x, v  .

Examples
= @cchisq(100, 100)

returns 0.51880....
@cellid—737

Cross-references
See also @chisq (p. 742), @dchisq (p. 830), @qchisq (p. 1047), and @rchisq (p. 1068).

@ceil Element Functions

Smallest number greater than or equal to (with optional precision).


Syntax: @ceil(x[, n])
x: number
n: (optional) integer
Return: number
• @ceil(x) returns x , the smallest integer that is greater than or equal to x.
n n
• @ceil(x, n) returns x  10  10 , the smallest decimal number that is greater than
or equal to x at the given precision.

The decimal offset n may be interpreted as the precision to use when computing the ceiling.
If n is not an integer, the integer floor n will be used.

Examples
= @ceil(@pi)

returns 4.
= @ceil(@pi,2)

returns 3.15.
= @ceil(-@pi)

returns -3.

Cross-references
See also @floor (p. 887).

@cellid Workfile Functions

Panel workfile series containing within cross-section identifier for observation.


Syntax: @cellid
Return: series

Returns index of the within cross-section identifier for each observation in the workfile.
• In a panel workfile, the index numbers identify the unique values of the within cross-
section dimension.
738—Function Reference: C

• In a non-panel workfile, the index numbers are equivalent to sequential observation


numbers.

Examples
wfcreate a 2001 2022 10
series ids = @cellid

creates a balanced 10 cross-section panel, with 22 observations per cross-section, and saves
a series with indices (1 to 22) corresponding to the year of the observation.

If we have an unbalanced panel


series ubids = @cellid

will contain indices uniquely identifying the values of the all of the within cross-section
identifiers observed in the workfile.

Thus, in a two-cross section panel where the first cross-section has annual observations for
1990, 1992, 1994, and 1995, and the second cross-section has observations for 1990, 1995,
and 1997, the corresponding index values will be of the form (1, 2, 3, 4) and (1, 4, 5),
respectively.

Cross-references
See also @obsrange (p. 705), @crossid (p. 772), and @obsid (p. 1016).

@cexp Element Functions

Exponential cumulative distribution.


Syntax: @cexp(x, m[, u])
x: number
m: number, m  0
u: (optional) number
Return: number

Computes the cumulative distribution function

 0 x0
F  x, m   
 1 – exp  – x  m  x0

If the optional argument u is non-zero, return the upper-tail value:

 1 x0
G  x, m   
 exp  – x  m  x0
@cfdist—739

Examples
= @cexp(@log(2), 1)

returns 0.5.

Cross-references
See also @dexp (p. 837), @qexp (p. 1047), and @rexp (p. 1072).

@cextreme Element Functions

Extreme value (Type I-minimum) cumulative distribution.


Syntax: @cextreme(x, [, u])
x: number
u: (optional) number
Return: number

Computes the cumulative distribution function


x
F  x   1 – exp  – e 
If the optional argument u is non-zero, return the upper-tail value:
x
G  x   exp  – e 
Examples
= @cextreme(-0.36651)

returns 0.50000....

Cross-references
See also @dextreme (p. 837), @qextreme (p. 1048), and @rextreme (p. 1072).

@cfdist Element Functions

F-distribution cumulative distribution.


Syntax: @cfdist(x, v 1 , v 2 [, u])
x: number
v1 : number, v 1  0
v2 : number, v 2  0
u: (optional) number
Return: number
740—Function Reference: C

Probability that an F-statistic with v 1 numerator degrees of freedom and v 2 denominator


degrees of freedom exceeds x .

Computes the cumulative distribution integral

 0
 x0
F  x v 1, v 2    x
 0 f  s v 1, v 2  ds x0

where
v 2 v 2
v 11 v 22 v – 2  2 – v  v   2
f  x v 1, v 2   -------------------------------------
-x 1  v2  v1 x  1 2
B  v 1  2, v 2  2 

for x  0 and 0 otherwise, and B is the beta function


1
a–1 b–1 G  a G  b 
B  a, b   t 1 – t dt  ------------------------
Ga  b
0

Note that the functions allow for fractional degrees of freedom parameters v 1 and v 2 .

If the optional argument u is non-zero, return the upper-tail value: 1 – F  x v 1, v 2  .

Examples
= @cfdist(1, 2, 2)

returns 0.5.

Cross-references
See also @fdist (p. 882), @dfdist (p. 838), @qfdist (p. 1048), and @rfdist (p. 1073).

@cfirst Matrix Column Statistics

First non-missing value in each column of a matrix object.


Syntax: @cfirst(m)
m: matrix
Return: vector

Returns a vector containing the first non-missing value from each column of the matrix m.

Examples
Let M1 be an n  n lower triangular matrix whose  n  n – 1    2 elements above the main
diagonal are NAs. In this case,
@cgamma—741

= @cfirst(m1)

returns the main diagonal of M1 as a column vector.

Cross-references
See also @clast (p. 748), @cifirst (p. 744), and @cilast (p. 745).

See also @first (p. 886), @last (p. 940), @ifirst (p. 914), and @ilast (p. 915).

@cgamma Element Functions

Gamma cumulative distribution.


Syntax: @cgamma(x, b, r[, u])
x: number
b: number, b  0
r: number, r  0
u: (optional) number
Return: number

Computes the cumulative distribution function

 0
 x0
F  x b, r    x
 0 f  s b, r  ds x0

where
–r r – 1 –x  b
b x e
f  s b, r   --------------------------------
Gr
for x  0 and 0 elsewhere.

If the optional argument u is non-zero, return the upper-tail value: 1 – F  x b, r 

Examples
= @cgamma(2.7725, 4, 1)

returns 0.49998....

Cross-references
See also @dgamma (p. 838), @qgamma (p. 1050), and @rgamma (p. 1074).
742—Function Reference: C

@cged Element Functions

Generalized error cumulative distribution.


Syntax: @cged(x, r[, u])
x: number
r: number, r  0
u: (optional) number
Return: number

Computes the cumulative distribution function


x
Fx r   f s r  ds
0

where
3 12  G  3---  
r2
rG  ---   
r   r   r  
f  s r   ------------------------- exp  – s  -------------- 
32
2G  --- 
1   G  1---   
r     r  

If the optional argument u is non-zero, return the upper-tail value: 1 – F  x r  .

Examples
Cross-references
= @cged(0.675, 2)

returns 0.75016.

See also @dged (p. 839), @qged (p. 1050), and @rged (p. 1074).

@chisq Element Functions

Upper tail of the Chi-square distribution.


Syntax: @chisq(x, v)
x: number
v: number, v  0
Return: number

Returns the probability that a Chi-squared statistic with v degrees of freedom exceeds x .
@cholesky—743

Computes the upper tail of the cumulative distribution function

 0
 x0
Gx v   
 x f  s v  ds x0

where
1 v  2 – 1 –s  2
f  s v   ------------------------------ s e
v2
2 Gv  2

Examples
= @chisq(100, 100)

returns 0.48119....

Cross-references
See also @cchisq (p. 736), @dchisq (p. 830), @qchisq (p. 1047), and @rchisq (p. 1068).

@cholesky Matrix Algebra

Cholesky factor of matrix.


Syntax: @cholesky(s)
s: sym
Return: matrix

Returns a matrix containing the Cholesky factorization of s .

The Cholesky factorization finds the lower triangular matrix L such that LL is equal to
the symmetric source matrix s .

Examples
sym s = @inner(@mrnd(10, 10))
matrix chol = @cholesky(s)
matrix orig1 = chol * chol.@t
sym orig2 = @inner(chol.@t)

computes the Cholesky, and uses it to recreate the original matrix. Note that ORIG1 is a
matrix object whereas ORIG2 is a sym object.

Inverting the Cholesky may be used to obtain the matrix inverse.


sym sinv1 = @inverse(s)
matrix invchol = @inverse(chol)
744—Function Reference: C

matrix sinv2 = invchol.@t * invchol


sym sinv3 = @inner(invchol)
matrix id1 = sinv1 * s
matrix id2 = sinv2 * s
matrix id3 = sinv3 * s

uses properties of the inverse of the Cholesky to recreate the matrix inverse so that ID1, ID2,
and ID3 are all different computations yielding the identity matrix.

Cross-references
See also @inverse (p. 926), @rank (p. 1063), @issingular (p. 931), @ltrim (p. 953), @qr
(p. 1055), @svd (p. 1137), and @svdfull (p. 1139).

@chr Element Functions | String Functions

ASCII value to string character.


Syntax: @chr(arg)
arg: integer
Return: string

Returns the character string corresponding to the ASCII value arg.

Valid inputs are integer values running from 0 to 255. Any invalid value will return an empty
string.

Examples
string s1 = @chr(67)
string s2 = @chr(99)

returns the strings S1=“C” and S2=“c”.

Cross-references
See also @asc (p. 717).

@cifirst Matrix Column Statistics

Index of the first non-missing value in each column of a matrix.


Syntax: @cifirst(m)
m: matrix
Return: vector
@cilast—745

Returns a vector containing the index (i.e, row number) of the first non-missing value of
each column of the matrix m.

Examples
Let M1 be an n  n lower triangular matrix whose  n  n – 1    2 elements above the main
diagonal are NAs. In this case,
= @cifirst(m1)

returns a column vector whose elements are the integers 1, 2, ..., n .

Cross-references
See also @cfirst (p. 740), @clast (p. 748), and @cilast (p. 745).

See also @first (p. 886), @last (p. 940), @ifirst (p. 914), and @ilast (p. 915).

@cilast Matrix Column Statistics

Index of the last non-missing value in each column of a matrix.


Syntax: @cilast(m)
m: matrix
Return: vector

Returns a vector containing the index (i.e, row number) of the last non-missing value of
each column of the matrix m.

Examples
Let M2 be an n  n upper triangular matrix whose  n  n – 1    2 elements below the main
diagonal are NAs. In this case,
= @cilast(m2)

returns a column vector whose elements are the integers 1, 2, ..., n .

Cross-references
See also @cfirst (p. 740), @clast (p. 748), and @cifirst (p. 744).

See also @first (p. 886), @last (p. 940), @ifirst (p. 914), and @ilast (p. 915).
746—Function Reference: C

@cimax Matrix Column Statistics

Index of the maximal value in each column of a matrix.


Syntax: @cimax(m)
m: matrix
Return: vector

Returns a vector containing the index (i.e, row number) of the maximal values of each col-
umn of the matrix m.

Examples
Let ID be an n  n identity matrix. Then
= @cimax(id)

returns a column vector whose elements are the integers 1, 2, ..., n .

Cross-references
See also @cimin (p. 746), @cmax (p. 750), and @cmin (p. 752).

@cimin Matrix Column Statistics

Index of the minimal value in each column of a matrix.


Syntax: @cimin(m)
m: matrix
Return: vector

Returns a vector containing the index (i.e, row number) of the minimal values of each col-
umn of m.

Examples
Let ID be an n  n identity matrix. Then
= @cimin(id)

returns a column n -vector whose elements are 2, 1, 1, ..., 1, i.e., a 2 followed by n – 1 1s.

Cross-references
See also @cimax (p. 746), @cmax (p. 750), and @cmin (p. 752).
@claplace—747

@cintercept Matrix Column Statistics

Intercept from a trend regression performed on each column of a matrix.


Syntax: @cintercept(m)
m: matrix
Return: vector

Returns a vector of intercepts from trend regressions, each the result of applying @inter-
cept to each column of m.

Examples
vector trend = @grid(0, 10000, 10001)
matrix m1 = @hcat(1+0.5*trend, 1+2*trend) + @mnrnd(10001, 2)
= @cintercept(m1)

produces a vector of two elements, both of which should be approximately 1.

Cross-references
See also @ctrendcoef (p. 775), @intercept (p. 925), and @trendcoef (p. 1151).

@claplace Element Functions

Laplace cumulative distribution.


Syntax: @claplace(x[, u])
x: number
u: (optional) number
Return: number

Computes the cumulative distribution integral


x
Fx   f  s  ds
–

where
1 –s
f  s   --- e
2
If the optional argument u is non-zero, return the upper-tail value: 1 – F  x  .

Examples
= @claplace(@log(2))
748—Function Reference: C

returns 0.75.

Cross-references
See also @dlaplace (p. 841), @qlaplace (p. 1051), and @rlaplace (p. 1080).

@clast Matrix Column Statistics

Last non-missing value in each column of the matrix.


Syntax: @clast(m)
m: matrix
Return: vector

Returns a vector containing the last non-missing value of each column of m.

Examples
Let M2 be an n  n upper triangular matrix whose  n  n – 1    2 elements below the main
diagonal are NAs. In this case,
= @clast(m2)

returns the main diagonal of M2 as a column vector.

Cross-references
See also @cfirst (p. 740), @cifirst (p. 744), and @cilast (p. 745).

See also @first (p. 886), @last (p. 940), @ifirst (p. 914), and @ilast (p. 915).

@clogistic Element Functions

Logistic cumulative distribution.


Syntax: @clogistic(x[, u])
x: number
u: (optional) number
Return: number

Computes the cumulative distribution function


1
F  x   -----------------------
–x
1  e 
If the optional argument u is non-zero, return the upper-tail value:
@clognorm—749

–x
e
G  x   -----------------------
–x
1  e 
Examples
= @clogistic(0)

returns 0.5.

Cross-references
See also @dlogistic (p. 843), @qlogistic (p. 1052), and @rlogistic (p. 1081).

@cloglog Element Functions

Complimentary log-log function.


Syntax: @cloglog(x)
x: number
Return: number

Compute the value of the complementary log-log function:


g  x   log  – log  1 – x  
for 0  x  1 .

Examples
= @cloglog(0.5)

returns -0.36651....

Cross-references
See also @clogistic (p. 748)

@clognorm Element Functions

Log normal cumulative distribution.


Syntax: @clognorm(x, m, s[, u])
x: number
m: number, m  0
s: number, s  0
u: (optional) number
Return: number
750—Function Reference: C

Computes the cumulative distribution function

 0
 x0
F  x m, s    x
 0 f  v m, s  dv x0

where

1  1 2
f  v m, s   ------------------- exp  – --------  log x – m  
2
x 2ps
2  2s 

If the optional argument u is non-zero, return the upper-tail value: 1 – F  x m, s  .

Examples
= @clognorm(1, 0, 2)

returns 0.5.

Cross-references
See also @dlognorm (p. 843), @qlognorm (p. 1052), and @rlognorm (p. 1082).

@cmax Matrix Column Statistics

Maximal value in each column of a matrix.


Syntax: @cmax(m)
m: matrix
Return: vector

Returns a vector containing the maximal values of each column of m.

Examples
Let ID be an n  n identity matrix. Then
= @cmax(id)

returns a column vector of n ones.

Cross-references
See also @cimax (p. 746), @cimin (p. 746), and @cmin (p. 752).
@cmedian—751

@cmean Matrix Column Statistics

Mean in each column of a matrix.


Syntax: @cmean(m)
m: matrix
Return: vector

Returns a vector containing the mean values of each column of the matrix m.

Examples
Let MAT be an m  n matrix of IID exponential numbers with mean 1. Then
= @cmean(mat)

returns an n -vector whose elements are approximately 1 for large m .

Cross-references
See also @csum (p. 774) and @coldemean (p. 756)

@cmedian Matrix Column Statistics

Median of each column of a matrix.


Syntax: @cmedian(m)
m: matrix
Return: vector

Returns a vector containing the median values of each column of m.

Examples
Let MAT be an m  n matrix of IID exponential numbers with mean 1. Then
= @cmean(mat)

returns an n -vector whose elements are approximately ln 2 for large m .

Cross-references
See also @cmean (p. 751) and @cquantile (p. 771).
752—Function Reference: C

@cmin Matrix Column Statistics

Minimal value for each column of the matrix.


Syntax: @cmin(m)
m: matrix
Return: vector

Returns a vector containing the minimal values of each column of the matrix m.

Examples
Let ID be an n  n identity matrix. Then
= @cmin(id)

returns a column vector of n zeros.

Cross-references
See also @cimax (p. 746), @cimin (p. 746), and @cmax (p. 750).

@cnas Matrix Column Statistics

Number of NA values in each column of a matrix.


Syntax: @cnas(m)
m: matrix
Return: vector

Returns a vector containing the number of missing values in each column of the matrix m.

Examples
Let M1 be an n  n lower triangular matrix whose  n  n – 1    2 elements above the main
diagonal are NAs. In this case,
= @cnas(m1)

returns a column vector whose elements are the integers 0, 1, ..., n – 1 .

Cross-references
See also @cobs (p. 754).
@cnorm—753

@cnegbin Element Functions

Negative binomial distribution cumulative probability.


Syntax: @cnegbin(x, n, p)
x: number
n: number, n  0
p: number, 0  p  1
Return: number

Computes the cumulative probability function


x
j –m
F  x, m   me  j! x0
j0

and
F  x, m   0 x0
where x is the integer floor of x .

Examples
= @cnegbin(9, 10, 0.5)

returns 0.5.

Cross-references
See also @dnegbin (p. 845), @qnegbin (p. 1053), and @rnegbin (p. 1087).

@cnorm Element Functions

Standard normal cumulative distribution.


Syntax: @cnorm(x[, u])
x: number
u: (optional) number
Return: number

Computes the cumulative distribution integral


x
Fx   f  s  ds
–

where
754—Function Reference: C

–1  2 2
f  s    2p  exp  – s  2 

If the optional argument u is non-zero, return the upper-tail value: 1 – F  x  .

Examples
= @cnorm(-1.96)

returns 0.02499....

Cross-references
See also @logcnorm (p. 950), @dnorm (p. 845), @qnorm (p. 1054), and @rnorm (p. 1087).

@cobs Matrix Column Statistics

Number of non-NA values in each column of a matrix.


Syntax: @cobs(m)
m: matrix
Return: vector

Returns a vector containing the number of non-missing values in each column of the matrix
m.

Examples
Let M1 be an n  n lower triangular matrix whose  n  n – 1    2 elements above the main
diagonal are NAs. In this case,
= @cobs(m1)

returns a column vector whose elements are the integers n , n – 1 , ..., 1.

Cross-references
See also @cnas (p. 752).

@colcumprod Matrix Utility

Cumulative products for each column of a matrix.


Syntax: @colcumprod(m)
m: matrix, vector
Return: matrix, vector

Returns a matrix where each column contains the cumulative products of the values of the
corresponding column of m.
@colcumsum—755

For each element of the output, compute the cumulative product of the values in m from the
start of the column up to the current row:
t
y  t, k    m  j, k 
j1

Note that this function is prone to numeric overflow.

Examples
Let M1 be an m  n matrix of IID uniform numbers drawn from the unit interval. Then
= @colcumprod(m1)

generates an m  n matrix whose n columns converge to 0 at an exponential rate.

Cross-references
See also @colcumsum (p. 755).

See also @cumprod (p. 797) and @cumsum (p. 802).

See also @cprod (p. 771), @csum (p. 774), and @csumsq (p. 774).

@colcumsum Matrix Utility

Cumulative sums for each column of a matrix.


Syntax: @colcumsum(m)
m: matrix, vector
Return: matrix, vector

Returns a matrix where each column contains the cumulative sums of the values of the cor-
responding column of m.

For each element of the output, compute the cumulative sum of the values in m from the
start of the column up to the current row:
t
y  t, k    m  j, k 
j1

Examples
Let M1 be an m  n matrix of IID uniform numbers drawn from the unit interval. Then
= @colcumsum(m1)

generates an m  n matrix whose n columns diverge to infinity at a linear rate.


756—Function Reference: C

Cross-references
See also @colcumprod (p. 754).

See also @cumprod (p. 797) and @cumsum (p. 802).

See also @cprod (p. 771), @csum (p. 774), and @csumsq (p. 774).

@coldemean Matrix Utility

Demean each column of a matrix.


Syntax: @coldemean(m)
m: matrix
Return: matrix

Returns the matrix containing the results from subtracting the column mean from each col-
umn of m.

For each element of the output matrix y :


y  t, k   m  t, k  – m̂ k

for m̂ k the mean of column k where


T
1
m̂ k  ----
T  m  j, k  (18.1)
j1

where T is the number of non-missing values in the column. If there are missing values in
a column, they are ignored and the number of rows is adjusted.

Examples
matrix m1 = @mnrnd(50, 4)
matrix m1d = @coldemean(m1)

demeans each column of M1 and places the results in M1D.

This operation is equivalent to


vector m1means = @cmeans(m1)
matrix m2d = m1 - @kronecker(@ones(m1.@rows), m1means.@t)

where @cmeans is used to compute the column means of M1.

Cross-references
See also @demean (p. 834), @detrend (p. 836), and @coldetrend (p. 757).
@coldetrend—757

@coldetrend Matrix Utility

Detrend each column of a matrix.


Syntax: @coldetrend(m)
m: matrix
Return: matrix

Returns the matrix containing the results from detrending each column of m.

Detrending produces the residuals of the OLS regression of the data in column k versus an
intercept and implicit time trend. For each element of the output matrix y :
y  t, k   m  t, k  – c k – b k  t – 1 

where c k and b k are the intercept and slope coefficients of a regression of the data in col-
umn k on a constant and time trend. If there are missing values in a column, they are
ignored.

Examples
matrix m1 = @mnrnd(50, 4)
matrix m1d = @coldetrend(m1)

detrends each column of M1 and places the results in M1D.

This operation is equivalent to


vector cintercepts = @cintercept(m1)
vector ctrendcs = @ctrendcoef(m1)
matrix m2d = m1 - @kronecker(@ones(m1.@rows), cintercepts.@t) -
@kronecker(@range(0, m1.@rows-1), ctrendcs.@t)

where @cintercept and @ctrendcoef are used to compute the coefficients of the column
trend regressions.

Cross-references
See also @cintercept (p. 747) and @ctrendcoef (p. 775).

See also @demean (p. 834), @detrend (p. 836), and @coldemean (p. 756).
758—Function Reference: C

@colpctiles Matrix Utility

Percentile values for each column of a matrix.


Syntax: @colpctiles(m[, o])
m: matrix, vector
o: (optional) string
Return: matrix, vector

Returns a matrix where each column contains the percentiles of the values of the corre-
sponding column of m

The option o controls the direction of the ranking: “a” (ascending - default) or “d” (descend-
ing).

Examples
Let MAT be a matrix with two columns. Then
= @colpctiles(mat)

and
= @hcat(@pctiles(mat.@col(1)), @pctiles(mat.@col(2)))

are equivalent.

Cross-references
See also @pctiles (p. 1035).

@colranks Matrix Utility

Ranks of each column of the matrix.


Syntax: @colranks(m[, o, t])
m: matrix, vector
o: (optional) string
t: (optional) string
Return: matrix, vector

Returns a matrix where each column contains the ranks of the values of the corresponding
column of m.

The o option controls the direction of the ranking:


• “a” (ascending - default) or “d” (descending).
@colsort—759

The t option controls tie-handling:


• Ties are broken according to the setting of t: “i” (ignore), “f” (first), “l” (last), “a”
(average - default), “r” randomize.

If you wish to specify tie-handling options, you must also specify the order option (e.g.,
@colranks(x, "a", "i")).

Examples
= @colranks(m1, "d")

returns a matrix whose i-th column ranks the elements in the i-th column of M1 so that the
largest element in said column has a rank of 1.

Cross-references
See also @sort (p. 1116), @colsort (p. 759), and @rowsort (p. 1091).

See also @ranks (p. 1064) and @rowranks (p. 1090).

See also @capplyranks (p. 733) and @rapplyranks (p. 1065).

@colsort Matrix Utility

Sort each column of the matrix.


Syntax: @colsort(m[, o])
m: matrix, vector
o: (optional) string
Return: matrix, vector

Returns a matrix where each column contains the sorted values of the corresponding col-
umn of m.

The option o controls the direction of the ranking: “a” (ascending - default) or “d” (descend-
ing).

Examples
Let M1 be a matrix. Then
= @colsort(m1, "d")

returns a matrix whose i-th column is the sorted (from largest at the top to smallest at the
bottom) version of the i-th column in M1.

Cross-references
See also @sort (p. 1116) and @rowsort (p. 1091).
760—Function Reference: C

See also @ranks (p. 1064), @colranks (p. 758), and @rowranks (p. 1090).

See also @capplyranks (p. 733) and @rapplyranks (p. 1065).

@colstdize Matrix Utility

Standardize each column using the sample (d.f. corrected) standard deviation.
Syntax: @colstdize(m)
m: matrix, vector
Return: matrix, vector

Returns the matrix containing the results from standardizing each column of m.

For each element of the output:


1
y  t, k   ----  m  t, k  – m̂ k 
sk

for m̂ k the mean and s k the sample (d.f. corrected) standard deviation of column k where
T
1
m̂ k  ----
T  m  j, k 
j1
(18.2)
1 T 2
sk  -------------
T–1   m  j, k  – m̂ k 
j1

where T is the number of non-missing values in the column. If there are missing values in
a column, they are ignored and the number of rows is adjusted.

Examples
matrix m1 = @mnrnd(50, 4)
matrix m1s = @colstdize(m1)

standardizes each column of M1 and places the results in M1D.

Cross-references
See also @stdize (p. 1121), @stdizep (p. 1122), @colstdizep (p. 761), and @coldemean
(p. 756).
@colstdizep—761

@colstdizep Matrix Utility

Standardize each column using the population (non-d.f. corrected) standard deviation.
Syntax: @colstdizep(m)
m: matrix, vector
Return: matrix, vector

Returns the matrix containing the results from standardizing each column of m.

For each element of the output:


1
y  t, k   -----  m  t, k  – m̂ k 
ĵ k

for m̂ k the mean and ĵ k the population (non-d.f. corrected) standard deviation of column k
where
T
1
m̂ k  ----
T  m  j, k 
j1
(18.3)
1 T 2
ĵ k  ----
T   m  j, k  – m̂ k 
j1

where T is the number of non-missing values in the column. If there are missing values in
a column, they are ignored and the number of rows is adjusted.

Examples
matrix m1 = @mnrnd(50, 4)
matrix m1s = @colstdizep(m1)

standardizes each column of M1 and places the results in M1D.

Cross-references
See also @colstdize (p. 760), @stdize (p. 1121), @stdizep (p. 1122), and @coldemean
(p. 756).
762—Function Reference: C

@columnextract Matrix Utility

Extract a column from the matrix.


Syntax: @columnextract(m, n)
m: matrix, sym
n: integer
Return: vector

Extract a vector from column n of the matrix object m, where m is a matrix object.

Note that we recommend that extraction be performed using the newer “.col” object data
member functions. See “Matrix Data Members” on page 556 and “Sym Data Members” on
page 992 in Object Reference and the examples below.

Examples
matrix m1 = @mnrnd(20, 5)
vector v1 = @columnextract(m1,3)

extracts column 3 from the matrix M1.


sym s1 = @mnrnd(5, 5)
vector v2 = @columnextract(s1, 5)

Alternately, using the data member functions, we have


vector v1a = m1.@col(3)
vector v2a = s1.@col(5)

Cross-references
See also @rowextract (p. 1089) and @subextract (p. 1133).

See “Matrix Data Members” on page 556 and “Sym Data Members” on page 992 in Object
Reference.

@columns Matrix Utility

Number of columns in matrix object or group.


Syntax: @columns(x)
m: matrix, sym, group
Return: integer
@cond—763

Examples
matrix m1 = @mnrnd(10, 3)
scalar sc1 = @columns(m1)

assigns the value 3 to the scalar object SC1.

Cross-references
See also @rows (p. 1090).

@commute Matrix Algebra

Commutation matrix.
Syntax: @commute(m, n)
m: integer
n: integer
Return: matrix

The commutation matrix transforms the vectorization of a matrix to the vectorization of its
transpose.

Given the m  n matrix A , returns the mn  mn matrix K , which satisfies


K  vec(A)  vec(A)

Examples
matrix m1 = @mnrnd(10, 5)
vector diff = @commute(10, 5) * @vec(m1) - @vec(m1.@t)

demonstrates the properties of the commutation matrix since DIFF equals zero.

Cross-references
See also @duplic (p. 849), @duplicinv (p. 850), and @elimin (p. 867).

@cond Matrix Algebra

Condition number of matrix.


Syntax: @cond(m[, n])
m: matrix, sym
n: (optional) integer
Return: number

Returns the condition number of a square matrix or sym, m.


764—Function Reference: C

The condition number is the product of the norm of the matrix divided by the norm of the
inverse.

If the norm option n is omitted, the infinity norm is used to determine the condition num-
ber. Possible norms are “-1” for the infinity norm, “0” for the Frobenius norm, and an inte-
n
ger “n” for the L norm.

Examples
matrix m1 = @mnrnd(10, 10)
scalar sc1 = @cond(m1)

computes the infinity norm of the matrix M1.


sym s1 = @inner(m1)
scalar sc2 = @cond(s1, 2)
2
computes the L norm of the symmetric matrix S1.

Cross-references
See also @norm (p. 1012)

@convert Matrix Utility

Converts series, alpha, or group to matrix objects after removing NAs.


Syntax: @convert(o[, s])
o: series, alpha, group
s: (optional) sample string or object
Return: vector, svector, matrix

Convert data in the series (numeric or alpha) or group object into a vector (numeric or
alpha) or group after removing rows with an NA or “”.
• If o is a series, @convert returns a vector from the values of o using the optional sam-
ple s or the current workfile sample. If any observation has the value “NA”, the obser-
vation will be omitted from the vector.
• If o is an alpha series, @convert returns an svector from the values of o using the
optional sample s or the current workfile sample.
• If o is a group, @convert returns a matrix from the values of o using the optional
sample object smp or the current workfile sample.
The data for series in o are placed in the columns of the resulting matrix in the order
they appear in the group spreadsheet. If any of the series for a given observation has
the value “NA”, the observation will be omitted for all series.
@convert—765

Note that if the group contains alpha series, they are treated as numeric series with all
NA values for purposes of this conversion.

For a conversion method that preserves NAs, see stomna (p. 599).

Examples
vector v2 = @convert(ser1)
vector v3 = @convert(ser2, "2000m12 2022m01")

converts the numeric series SER1 and SER2 into the vectors V2 and V3. V2 contains all non-
missing elements in the current workfile sample, while V3 contains non-missing elements
from 2000m12 to 2022m01.
sample smpl "2000m10 2022m05"
svector a2 = @convert(alp1)
svector a3 = @convert(alp2, smpl)

converts the alpha series ALP1 and ALP2 into the svectors A2 and A3. A2 contains all non-
missing (non-blank) elements in the current workfile sample, while A3 contains non-miss-
ing elements from 2000m10 to 2022m05.
matrix m1 = @convert(grp1)
matrix m2 = @convert(grp1, smpl)

converts the series in the group GRP1 into the matrices M1 and M2.

M1 uses all non-missing observations in the current workfile sample, while M2 uses non-
missing observations in the sample object from 2000m10 to 2022m05. Note that if GRP1 con-
tains alpha series, they are treated as numeric series with all NA values for purposes of this
conversion.

Cross-references
See also mtos (p. 522), stom (p. 598), stomna (p. 599), and ttom (p. 617).
766—Function Reference: C

@cor Basic Statistics

Computes the correlation between two vectors, or between the columns of a matrix.
Syntax: @cor(x, y)
x: vector, rowvector, or series
y: vector, rowvector, or series
Return: scalar

Syntax: @cor(m)
m: matrix object or group
Return: sym

For series and group calculations, EViews will use the current workfile sample.

Examples
If used with two vector or series objects, @cor returns the correlation between the two vec-
tors or series.
scalar sc1 = @cor(v1, v2)

If used with a matrix object or group, @cor calculates the correlation matrix between the
columns of the matrix object or the series in the group object.
sym s1 = @cor(mat1)

Cross-references
See also @cov (p. 767), @covp (p. 768), and @covs (p. 769).

@cos Element Functions

Cosine of argument specified in radians.

Compute the cosine of x (specified in radians).


Syntax: @acos(x)
x: number
Return: number

Examples
= @cos(@pi)

returns -1.
@cov—767

Cross-references
See also @acos (p. 714), @asin (p. 717), @atan (p. 718), @sin (p. 1112), and @tan
(p. 1144).

@cov Basic Statistics

Compute population (non-d.f. corrected) covariance between two vectors, or between the
columns of a matrix.
Syntax: @cov(v1, v2)
v1: vector, rowvector, or series
v2: vector, rowvector, or series
Return: scalar

Syntax: @cov(o)
o: matrix object or group
Return: sym

Compute covariances using n as the divisor in the moment calculation.

For series and group calculations, EViews will use the current workfile sample.

Examples
If used with two vector or series objects, @cov returns the population covariance between
the two vectors or series.
scalar sc1 = @cov(v1, v2)

If used with a matrix object or group, @cov calculates the population covariance matrix
between the columns of the matrix object or the series in the group object.
sym s1 = @cov(mat1)

Cross-references
See also @cor (p. 766), @covp (p. 768), and @covs (p. 769).
768—Function Reference: C

@covp Basic Statistics

Compute population (non-d.f. corrected) covariance between two vectors, or between the
columns of a matrix.
Syntax: @covp(v1, v2)
v1: vector, rowvector, or series
v2: vector, rowvector, or series
Return: scalar

Syntax: @covp(o)
o: matrix object or group
Return: sym

Compute covariances using n as the divisor in the moment calculation.

Equivalent to @cov (p. 767).

For series and group calculations, EViews will use the current workfile sample.

Examples
If used with two vector or series objects, @covp returns the population covariance between
the two vectors or series.
scalar sc1 = @covp(v1, v2)

If used with a matrix object or group, @covp calculates the population covariance matrix
between the columns of the matrix object.
sym s1 = @covp(mat1)

Cross-references
See also @cor (p. 766), @cov (p. 767), and @covs (p. 769).
@cpareto—769

@covs Basic Statistics

Compute sample (d.f. corrected) covariance between two vectors, or between the columns
of a matrix.
Syntax: @covs(v1, v2)
v1: vector, rowvector, or series
v2: vector, rowvector, or series
Return: scalar

Syntax: @covs(o)
o: matrix object or group
Return: sym

Compute covariances using n – 1 as the divisor in the moment calculation.

For series and group calculations, EViews will use the current workfile sample.

Examples
If used with two vector or series objects, @covs returns the sample covariance between the
two vectors or series.
scalar sc1 = @covs(v1, v2)

If used with a matrix object or group, @covs calculates the sample covariance matrix
between the columns of the matrix object.
sym s1 = @covs(mat1)

Cross-references
See also @cor (p. 766), @cov (p. 767), and @covp (p. 768).

@cpareto Element Functions

Pareto cumulative distribution.


Syntax: @cpareto(x, k, a[, u])
x: number
k: number, k  0
a: number, a  0
u: (optional) number
Return: number
770—Function Reference: C

Computes the cumulative distribution function

 0 xk
F  x, k, a    a
1 – k  x xk

If the optional argument u is non-zero, return the upper-tail value:

 1 xk
G  x, k, a    a
k  x xk

Examples
= @cpareto(2, 1, 2)

returns 0.75.

Cross-references
See also @dpareto (p. 846), @qpareto (p. 1054), and @rpareto (p. 1092).

@cpoisson Element Functions

Poisson distribution cumulative probability.


Syntax: @cpoisson(x, m)
x: number
m: number, m  0
Return: number

Computes the cumulative probability function


x
j –m
F  x, m   me  j! x0
j0

and
F  x, m   0 x0
where x is the integer floor of x .

Examples
= @cpoisson(10, 10)

returns 0.58303....

Cross-references
See also @dpoisson (p. 846), @qpoisson (p. 1055), and @rpoisson (p. 1092).
@cquantile—771

@cprod Matrix Column Statistics

Product of elements in each column of a matrix.


Syntax: @cprod(m)
m: matrix
Return: vector

Returns a vector containing the column products. One should be aware of overflow.

Examples
vector colprods = @cprod(m1)

computes the column products for the matrix M1 and places them in COLPRODS.

Cross-references
See also @colcumprod (p. 754) and @colcumsum (p. 755).

See also @cumprod (p. 797) and @cumsum (p. 802).

See also @csum (p. 774) and @csumsq (p. 774).

@cquantile Matrix Column Statistics

Quantiles for each column of a matrix.


Syntax: @cquantile(m, q)
m: matrix
q: number
Return: vector

Returns the column q-quantile using the Cleveland definition. q must be between zero and
one.

Examples
Let M1 be a matrix. Then
= @cquantile(m1, .5)

and
= @cmedian(m1)

are equivalent.
772—Function Reference: C

Cross-references
See also @cmedian (p. 751).

@crossid Workfile Functions

Panel workfile series containing cross-section identifier (index) for observation.


Syntax: @crossid
Return: series

Returns the index of the cross-section identifier for each observation in the workfile.
• In a panel workfile, the index numbers identify the cross-section.
• In a non-panel workfile, there is a single cross-section, so the function returns 1.

Examples
wfcreate a 2001 2022 10
series ids = @crossid

returns a series with integer index values identifying the cross-section.

If you have an unbalanced panel,


series ids = @crossid
ids.freq

displays a one-way tabulation of the cross-section ids, so that you can see the number of
observations in each cross-section.

Cross-references
See also @obsrange (p. 1017), @cellid (p. 737), and @obsid (p. 1016).

@cstdev Matrix Column Statistics

Sample standard deviation (d.f. corrected) of each column of a matrix.


Syntax: @cstdev(m)
m: matrix
Return: vector

Returns the column sample standard deviation.

Examples
= @cstdev(mat)
@cstdevs—773

returns a (column) vector whose i-th element is the sample standard deviation of the i-th
column of MAT.

Cross-references
See also @cmean (p. 751) and @cstdevs (p. 773).

@cstdevp Matrix Column Statistics

Population standard deviation (non-d.f. corrected) of each column of a matrix.


Syntax: @cstdevp(m)
m: matrix
Return: vector

Returns the column population standard deviation.

Examples
= @cstdevp(mat)

returns a (column) vector whose i-th element is the population standard deviation of the i-th
column of MAT.

Cross-references
See also @cstdev (p. 772) and @cstdevs (p. 773).

@cstdevs Matrix Column Statistics

Sample standard deviation (d.f. corrected) of each column of a matrix


Syntax: @cstdevs(m)
m: matrix
Return: vector

Returns the column sample standard deviation.

Examples
= @cstdevs(mat)

returns a (column) vector whose i-th element is the sample standard deviation of the i-th
column of MAT.

Cross-references
See also @cstdev (p. 772) and @cstdevp (p. 773).
774—Function Reference: C

@csum Matrix Column Statistics

Sum of the values in each column of a matrix.


Syntax: @csum(m)
m: matrix
Return: vector

Returns a vector containing the summation of the rows in each column of the matrix m.

Examples
vector colsums = @csum(m1)

computes the column sums for the matrix M1 and places them in COLSUMS.

Cross-references
See also @colcumprod (p. 754) and @colcumsum (p. 755).

See also @cumprod (p. 797) and @cumsum (p. 802).

See also @cprod (p. 771) and @csumsq (p. 774).

@csumsq Matrix Column Statistics

Sum of the squared values in each column of a matrix.


Syntax: @csumsq(m)
m: matrix
Return: vector

Returns the sum of squared values for each column of m.

Examples
vector colsumsqs = @csumsq(m1)

computes the column sums-of-squares for matrix M1 and places them in COLSUMSQS.

Cross-references
See also @colcumprod (p. 754) and @colcumsum (p. 755).

See also @cumprod (p. 797) and @cumsum (p. 802).

See also @cprod (p. 771) and @csum (p. 774).


@ctrendcoef—775

@ctdist Element Functions

Student’s t cumulative distribution.


Syntax: @ctdist(x, v[, u])
x: number
v: number, v  0
u: (optional) number
Return: number
x
Fx v   f  s, v  ds
–

where
v1
G  ------------  – v  1 
--------------------
 2  2
s  2
 
f  s v   ------------------------------ 1  ----
1---   v 
2 v 
 vp  G ---
2 

If the optional argument u is non-zero, return the upper-tail value: 1 – F  x, v  .


Note that v  1 , yields the Cauchy distribution.

Examples
= @ctdist(-12.71, 1)

returns 0.02499....

Cross-references
See also @tdist (p. 1144), @dtdist (p. 847), @qtdist (p. 1056), and @rtdist (p. 1099).

@ctrendcoef Matrix Column Statistics

Slope from a trend regression on each column of a matrix.


Syntax: @ctrendcoef(m)
m: matrix
Return: vector

Returns a vector of slopes from a trend regression, each the result of applying @trendcoef
to the columns of m.
776—Function Reference: C

Examples
vector trend = @grid(0, 10000, 10001)
matrix m1 = @hcat(1+0.5*trend, 1+2*trend) + @mnrnd(10001, 2)
= @ctrendcoef(m1)

produces a vector of two elements, the first of which should be close to 0.5, the second of
which should be approximately 2.

Cross-references
See also @cintercept (p. 747), @intercept (p. 925), and @trendcoef (p. 1151).

@ctrmean Matrix Column Statistics

Trimmed mean of each column of a matrix.


Syntax: @ctrmean(m, p)
m: matrix
p: number
Return: vector

Returns a vector of trimmed means, each the result of applying @trmean to columns of m.

Examples
matrix m = @mrnd(100,10)
m(1,1) = 1000
= @cmean(m)

returns a vector of column means of M, the first of which should be approximately 10.495,
the rest of which should be around 0.5.
= @ctrmean(m,1)

returns a vector of trimmed column means of M, all of which should be approximately 0.5.

Cross-references
See also @trmean (p. 1154).
@cumbmean—777

@cumbmax Cumulative Statistics

Backward cumulative maximums of a series.

Decreasing samples calculation of the maximum.


Syntax: @cumbmax(x, [s])
x: series
s: (optional) sample string or object
Return: series

The backward maximum for each observation t may be written as the maximum value
from the current observation to the last period, so that
y t  x t  t 

where the order statistics  x t  1 , x t  2 , , x t  t   represent data for the t  T – t  1


observations ( t, T ), ordered from low to high, where T is the last period.This function is
panel aware.

Examples
show @cumbmax(x)

generates a linked series of the backward cumulative maximum of the series x.

Cross-references
See also @cumbmin (p. 779).

For the forward variant of this function, see @cummax (p. 793).

@cumbmean Cumulative Statistics

Backward cumulative means of a series.

Decreasing samples calculation of the mean of the values in x.


Syntax: @cumbmean(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the mean of the values in x from t to the end of the workfile or from t to the end
of the optional sample s:
778—Function Reference: C

T
1
y t  ----  x j
t j  t

where T is the last period of the cumulative process, and t  T – t  1 .

This function is panel aware.

Examples
show @cumbmean(x)

generates a linked series of the backward cumulative mean of the observations in series x.

Cross-references
See also @cumbsum (p. 786), @cumbsumsq (p. 786), and @cumbprod (p. 781).

For the forward variant of this function, see @cummean (p. 794).

@cumbmedian Cumulative Statistics

Backward cumulative median of a series.

Decreasing samples calculation of the median.


Syntax: @cumbmedian(x, [s])
x: series
s: (optional) sample string or object
Return: series

The median for each observation t may be written as:

 x t   t  1   2  t is odd

yt   x  x t  t  2  1 
t  t  2  t is even
 -----------------------------------------------
-
 2

where order statistics  x t  1 , x t  2 , , x t  t   represent data for the t  T – t  1 obser-


vations ( t, T ), ordered from low to high, and T is the last period.

This function is panel aware.

Examples
show @cumbmedian(x)

generates a linked series of the backward cumulative median of the series x.


@cumbmin—779

Cross-references
See also @cumbquantile (p. 782).

For the forward variant of this function, see @cummedian (p. 794).

@cumbmin Cumulative Statistics

Backward cumulative minimum of a series.

Decreasing samples calculation of the minimum.


Syntax: @cumbmin(x, [s])
x: series
s: (optional) sample string or object
Return: series

The backward maximum as the minimum value from the current observation to the end of
the sample, so that:
yt  xt  1 

where the order statistics  x t  1 , x t  2 , , x t  t   represent data for the t  T – t  1


observations ( t, T ), ordered from low to high, and T is the last period.

This function is panel aware.

Examples
show @cumbmin(x)

generates a linked series of the backward cumulative minimum of the series x.

Cross-references
See also @cumbmax (p. 777).

For the forward variant of this function, see @cummin (p. 795).
780—Function Reference: C

@cumbnas Cumulative Statistics

Backward cumulative missing observations of a series.

Increasing samples calculation of the missing (NA) observations in x .


Syntax: @cumbnas(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the number of missing (NA) values in x from t to the end of the workfile or from
t to the end of the optional sample s.
This function is panel aware.

Examples
series x = @recode(@rnd > 0.5, @nrnd, na)
show x @cumbnas(x)

produces a spreadsheet with two columns correspond to x and @cumbnas(x). The second
series (which corresponds to @cumbnas(x)) starts at the count returned by @nas(x) and
decrements in those observations where x is NA.

Cross-references
See also @cumbobs (p. 780).

For the forward variant of this function, see @cumnas (p. 796).

@cumbobs Cumulative Statistics

Backward cumulative observations of a series.

Increasing samples calculation of the number of non-missing observations in x .


Syntax: @cumbobs(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the number of non-missing values in x from t to the end of the workfile or from t
to the end of the optional sample s.

This function is panel aware.


@cumbprod—781

Examples
series x = @recode(@rnd > 0.5, @nrnd, na)
show x @cumbobs(x)

produces a spreadsheet with two columns correspond to x and @cumbobs(x). The second
series (which corresponds to @cumbobs(x)) starts at the count returned by @obs(x) and
decrements in those observations where x is non-NA.

Cross-references
See also @cumbnas (p. 780).

For the forward variant of this function, see @cumobs (p. 797).

@cumbprod Cumulative Statistics

Backward cumulative products of a series.

Decreasing samples calculation of the product of the values in x.


Syntax: @cumbprod(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the product of the values in x from t to the end of the workfile or from t to the
end of the optional sample s:
T
yt   xj
jt

where T is the last period of the cumulative process. Note that this function is prone to
numeric overflow.

This function is panel aware.

Examples
show @cumbprod(x)

generates a linked series of the backward cumulative product of the observations in series x.

Cross-references
See also @cumbsum (p. 786), @cumbmean (p. 777), and @cumbsumsq (p. 786).

For the forward variant of this function, see @cumprod (p. 797).
782—Function Reference: C

@cumbquantile Cumulative Statistics

Cumulative quantiles of a series.

Increasing samples calculation of the quantile value where approximately 100*q percent of
the data is less than or equal to the value,
Syntax: @cumbquantile(x, q, [s])
x: series
q: number, series
s: (optional) sample string or object
Return: series
• The quantile value q must satisfy 0  q  1 .
• The cumulative quantiles are computed using the Rankit-Cleveland definition of the
empirical distribution function: F  x t  r     r – 1  2   t .

To compute the cumulative backward quantile for observation t find r , the smallest rank
such that:
q  F  xt r  

where the order statistics  x t  1 , x t  2 , , x t  t   represent data for the t  T – t  1


observations ( t, T ), ordered from low to high, and T is the last period. For purposes of
computing F , tied ranks are assumed to take the last tied value.

Then the quantile is computed as:

 xt  1  if F  x t  1    q

y t    1 – d x t  r – k   dx t  r  if F  x t  r – k    q  F  x t  r  

 NA if F  x t  t    q

where the interpolating constant is


q – F  xt  r – k  
d  ---------------------------------------------------
-
F  xt  r   – F  xt  r – k  

for k  0 the smallest integer where F  x t  r – k    q . In the leading case where there are no
tied x t  r  values, k  1 .

This function is panel aware.

Examples
show @cumbquantile(x, 0.1)
@cumbstdev—783

generates a linked series of the backward cumulative 10th percentile of the series x.

Cross-references
See also @cumbmedian (p. 778).

For the forward variant of this function, see @cumquantile (p. 798).

@cumbstdev Cumulative Statistics

Backward cumulative standard deviations (d.f. adjusted) of a series.

Equivalent to @cumbstdevs.

Decreasing sample calculation of the square root of the sample (d.f. adjusted) Pearson prod-
uct moment variance.
Syntax: @cumbstdev(x, [s])
x: series
s: (optional) sample string or object
Return: series

The sample standard deviation is calculated for each observation t as:


T 2
 xj – xt 
yt   ----------------------
t – 1
jt

where T is the last period of the cumulative process, t  T – t  1 , and x t is the mean
of x over the last T – t  1 observations.

Examples
show @cumbstdev(x)

generates a linked series of the backward cumulative sample standard deviations of the
series x.

Cross-references
See also @cumbstdevs (p. 785), @cumbstdevp (p. 784), @cumbvar (p. 787), @cumbvarp
(p. 788), and @cumbvars (p. 789).

For the forward variant of this function, see @cumstdev (p. 799).
784—Function Reference: C

@cumbstdevp Cumulative Statistics

Backward cumulative standard deviations (population, non-d.f. corrected).

Decreasing samples calculation of the square root of the population (non-d.f. adjusted) Pear-
son product moment variance.
Syntax: @cumbstdevp(x, [s])
x: series
s: (optional) sample string or object
Return: series

The population standard deviation is calculated for each observation t as:


T 2
 xj – xt 
yt   ----------------------
t
jt

where T is the last period of the cumulative process, t  T – t  1 , and x t is the mean
of x over the last T – t  1 observations.

This function is panel aware.

Examples
show @cumbstdevp(x)

generates a linked series of the backward cumulative population standard deviations of the
series x.

Cross-references
See also @cumbstdev (p. 783), @cumbstdevs (p. 785), @cumbvar (p. 787), @cumbvarp
(p. 788), and @cumbvars (p. 789).

For the forward variant of this function, see @cumstdevp (p. 800).
@cumbstdevs—785

@cumbstdevs Cumulative Statistics

Backward cumulative sample standard deviations (sample, d.f. corrected) of a series.

Decreasing sample calculation of the square root of the sample (d.f. corrected) Pearson
product moment variance.
Syntax: @cumbstdevs(x, [s])
x: series
s: (optional) sample string or object
Return: series

The sample standard deviation is calculated for each observation t as:


T 2
 xj – xt 
yt   ----------------------
t – 1
jt

where T is the last period of the cumulative process, t  T – t  1 , and x t is the mean
of x over the last T – t  1 observations.

This function is panel aware.

Examples
show @cumbstdevs(x)

generates a linked series of the backward cumulative sample standard deviations of the
series x.

Cross-references
See also @cumbstdev (p. 783), @cumbstdevp (p. 784), @cumbvar (p. 787), @cumbvarp
(p. 788), and @cumbvars (p. 789).

For the forward variant of this function, see @cumstdevs (p. 801).
786—Function Reference: C

@cumbsum Cumulative Statistics

Backward cumulative sums of a series.

Decreasing samples calculation of the sum of the values in x.


Syntax: @cumbsum(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the sum of the values in x from t to the end of the workfile or from t to the end of
the optional sample s:
T
yt   xj
jt

where T is the last period of the cumulative process.

This function is panel aware.

Examples
show @cumbsum(x)

generates a linked series of the backward cumulative sum of the observations in series x.

Cross-references
See also @cumbmean (p. 777), @cumbsumsq (p. 786), and @cumbprod (p. 781).

For the forward variant of this function, see @cumsum (p. 802).

@cumbsumsq Cumulative Statistics

Backward cumulative sums of squares of a series.

Decreasing samples calculation of the sum of the squared values in x.


Syntax: @cumbsumsq(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the sum of the squared values in x from t to the end of the workfile or from t to
the end of the optional sample s:
@cumbvar—787

T
2
yt   xj
jt
where T is the last period of the cumulative process.
This function is panel aware.

Examples
show @cumbsumsq(x)

generates a linked series of the backward cumulative sums of squares of the series x.

Cross-references
See also @cumbsum (p. 786), @cumbmean (p. 777), and @cumbprod (p. 781).

For the forward variant of this function, see @cumsumsq (p. 803).

@cumbvar Cumulative Statistics

Backward cumulative variances (non-d.f. corrected) of a series.

Equivalent to @cumbvarp.

Decreasing samples calculation of the population (non-d.f. corrected) Pearson product


moment variance.
Syntax: @cumbvar(x, [s])
x: series
s: (optional) sample string
Return: series

The population variance for each observation t is calculated as:


T 2
 xj – xt 
yt   ----------------------
t
jt

where T is the last period of the cumulative process, t  T – t  1 , and x t is the mean
of x over the last T – t  1 observations.

This function is panel aware.

Examples
show @cumbvar(x)

generates a linked series of the backward cumulative population variance of the series x.
788—Function Reference: C

Cross-references
See also @cumbstdev (p. 783), @cumbstdevs (p. 785), @cumbstdevp (p. 784), @cumbvarp
(p. 788), and @cumbvars (p. 789).

For the forward variant of this function, see @cumvar (p. 803).

@cumbvarp Cumulative Statistics

Backward cumulative variance (population, non-d.f. corrected) of a series.

Decreasing samples calculation of the population (non-d.f. corrected) Pearson product


moment variance.
Syntax: @cumbvarp(x, [s])
x: series
s: (optional) sample string
Return: series

The population variance for each observation t is calculated as


T 2
 xj – xt 
yt   ----------------------
t
jt

where T is the last period of the cumulative process, t  T – t  1 , and x t is the mean
of x over the last T – t  1 observations.

Examples
show @cumbvarp(x)

generates a linked series of the backward cumulative population variance of the series x.

Cross-references
See also @cumbstdev (p. 783), @cumbstdevs (p. 785), @cumbstdevp (p. 784), @cumbvar
(p. 787), and @cumbvars (p. 789).

For the forward variant of this function, see @cumvarp (p. 804).
@cumbvars—789

@cumbvars Cumulative Statistics

Backward cumulative variances (sample, d.f. corrected) of a series.

Decreasing samples calculation of the sample (d.f. corrected) Pearson product moment vari-
ance.
Syntax: @cumbvars(x, [s])
x: series
s: (optional) sample string or object
Return: series

The sample variance for each observation t is calculated as:


T 2
 xj – xt 
yt   ----------------------
t – 1
jt

where T is the last period of the cumulative process, t  T – t  1 , and x t is the mean
of x over the last T – t  1 observations.

This function is panel aware.

Examples
show @cumbvars(x)

generates a linked series of the backward cumulative sample variance of the series x.

Cross-references
See also @cumbstdev (p. 783), @cumbstdevs (p. 785), @cumbstdevp (p. 784), @cumbvar
(p. 787), and @cumbvarp (p. 788).

For the forward variant of this function, see @cumvars (p. 805).
790—Function Reference: C

@cumdn Cumulative Statistics

Cumulative process of negative (below threshold) changes.

Compute the partial sum process of negative (below the threshold y) changes in the series
beginning in the specified date.
Syntax: @cumdn(x, d[, y, s])
x: series
d: string
y: (optional) number
s: (optional) sample string or object
Return: series

Consider the partial sum decomposition of a variable z t given a initial value z 0 as


+ – 0 + – 0
z t  z 0  z t  z t  z t where z t , z t , and z t are the partial sum processes of the differ-
ences for positive, negative, and zero changes in z t relative to the threshold y:
t
+
zt   z s  I  z s  y 
s1
t

zt   z s  I  z s  y 
s1
t
0
zt   z s  I  z s  y 
s1

This function returns the negative partial sums z t for the current or specified sample.
• The date d specification determines t  1 .
• Values for dates prior to d will be NAs.
• The optional y argument specifies the threshold value. By default y  0 .

This function is panel aware.

Examples
The code below produces a graph of a sine wave x and @cumdn applied on x.
wfcreate u 50
series x = @sin(@pi*@trend/4)
group g x @cumdn(x,1)
g.line
@cumdp—791

Cross-references
See also @cumdp (p. 791), @cumdz (p. 792), @dcumdp (p. 832), @dcumdn (p. 831), and
@dcumdz (p. 833).

@cumdp Cumulative Statistics

Cumulative process of positive (above threshold) changes.

Compute the partial sum process of positive (above the threshold y) changes in the series x
beginning in the specified date.
Syntax: @cumdp(x, d[, y, s])
x: series
d: string
y: (optional) number
s: (optional) sample string or object
Return: series

Consider the partial sum decomposition of a variable z t given a initial value z 0 as


+ – 0 + – 0
z t  z 0  z t  z t  z t where z t , z t , and z t are the partial sum processes of the differ-
ences for positive, negative, and zero changes in z t relative to the threshold y:
t
+
zt   z s  I  z s  y 
s1
t

zt   z s  I  z s  y 
s1
t
0
zt   z s  I  z s  y 
s1
+
This function returns the positive partial sums z t for the current or specified sample.
• The date d string specification determines t  1 .
• Values for dates prior to d will be NAs.
• The optional y argument specifies the threshold value. By default y  0 .

This function is panel aware.

Examples
The code below produces a graph of a sine wave x and @cumdp applied on x.
wfcreate u 50
792—Function Reference: C

series x = @sin(@pi*@trend/4)
group g x @cumdp(x,1)
g.line

Cross-references
See also @cumdn (p. 790), @cumdz (p. 792), @dcumdp (p. 832), @dcumdn (p. 831), and
@dcumdz (p. 833).

@cumdz Cumulative Statistics

Cumulative process of zero (at threshold) changes.

Compute the partial sum process of positive (at the threshold y) changes in the series x
beginning in the specified date.
Syntax: @cumdz(x, d[, y, s])
x: series
d: string
y: (optional) number
s: (optional) sample string or object
Return: series

Consider the partial sum decomposition of a variable z t given a initial value z 0 as


+ – 0 + – 0
z t  z 0  z t  z t  z t where z t , z t , and z t are the partial sum processes of the differ-
ences for positive, negative, and zero changes in z t relative to the threshold y:
t
+
zt   z s  I  z s  y 
s1
t

zt   z s  I  z s  y 
s1
t
0
zt   z s  I  z s  y 
s1
0
This function returns the zero change z t for the current or specified sample.
• The date d string specification determines t  1 .
• Values for dates prior to d will be NAs.
• The optional y argument specifies the threshold value. By default y  0 .

This function is panel aware.


@cummax—793

Examples
show @cumdz(x, 2001, 1)

produces a linked series of @cumdz applied to x where the starting date is 2001 and the
threshold value is set to 1.

Cross-references
See also @cumdn (p. 790), @cumdp (p. 791), @dcumdp (p. 832), @dcumdn (p. 831), and
@dcumdz (p. 833).

@cummax Cumulative Statistics

Cumulative maximum of a series.

Increasing samples calculation of the maximum.


Syntax: @cummax(x, [s])
x: series
s: (optional) sample string or object
Return: series

The maximum for each observation t may be written as


yt  xt  t 

where the order statistics  x t  1 , x t  2 , , x t  t   represent data from the beginning of the
workfile or sample s, up to the current observation ( 1, t ), ordered from low to high.

This function is panel aware.

Examples
series x = @cummax(@rnd)

generates a random process x that converges in probability to 1.

Cross-references
See also @cummin (p. 795).

For the backward variant of this function, see @cumbmax (p. 777).
794—Function Reference: C

@cummean Cumulative Statistics

Cumulative means of a series.

Increasing samples calculation of the mean of the values in x.


Syntax: @cummean(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the cumulative mean of the values in x from the start of the workfile or sample s,
up to the current observation:
t
1
y t  ---
t  xj
j1

This function is panel aware.

Examples
series x = @cummean(@nrnd)

generates a random process x that converges in probability to 0.

Cross-references
See also @cumsum (p. 802), @cumsumsq (p. 803), and @cumprod (p. 797).

For the backward variant of this function, see @cumbmean (p. 777).

@cummedian Cumulative Statistics

Cumulative median of a series.

Increasing samples calculation of the median.


Syntax: @cummedian(x, [s])
x: series
s: (optional) sample string or object
Return: series

The median for each observation t may be written as


@cummin—795

 xt   t  1   2  t is odd

yt   x
t  t  2   xt  t  2  1  t is even
 --------------------------------------------
 2

where the order statistics  x t  1 , x  2 , , x t  t   represent data from the beginning of the
workfile or sample s, up to the current observation ( 1, t ), ordered from low to high.

This function is panel aware.

Examples
series x = @cummedian(@rnd)

generates a random process x that converges in probability to 0.5.

Cross-references
See also @cumquantile (p. 798).

For the backward variant of this function, see @cumbmedian (p. 778).

@cummin Cumulative Statistics

Cumulative minimum of a series.

Increasing samples calculation of the minimum.


Syntax: @cummin(x, [s])
x: series
s: (optional) sample string or object
Return: series

The minimum for each observation t may be written as


yt  xt  1 

where the order statistics  x t  1 , x t  2 , , x t  t   represent data from the beginning of the
workfile or sample s, up to the current observation ( 1, t ), ordered from low to high.

This function is panel aware.

Examples
series x = @cummin(@rnd)

generates a random process x that converges in probability to 0.


796—Function Reference: C

Cross-references
See also @cummax (p. 793).

For the backward variant of this function, see @cumbmin (p. 779).

@cumnas Cumulative Statistics

Cumulative missing observations of a series.

Increasing samples calculation of the missing (NA) observations in x .


Syntax: @cumnas(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the number of missing (NA) values in x from the start of the workfile or sample s,
up to the current observation.

This function is panel aware.

Examples
series x = @recode(@rnd > 0.5, @nrnd, na)
show x @cumnas(x)

produces a spreadsheet with two columns correspond to x and @cumnas(x). The second
series (which corresponds to @cumnas(x)) starts at 0 (if the first observation in x is non-
NA) or 1 (if the first observation in x is NA) and increments in those observations where x
is NA.

Cross-references
See also @cumobs (p. 797).

For the backward variant of this function, see @cumbnas (p. 780).
@cumprod—797

@cumobs Cumulative Statistics

Cumulative observations of a series.

Increasing samples calculation of the number of non-missing observations in x .


Syntax: @cumobs(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the number of non-missing values in x from the start of the workfile or sample s,
up to the current observation.

This function is panel aware.

Examples
series x = @recode(@rnd > 0.5, @nrnd, na)
show x @cumobs(x)

produces a spreadsheet with two columns correspond to x and @cumobs(x). The second
series (which corresponds to @cumobs(x)) starts at 0 (if the first observation in x is NA) or
1 (if the first observation in x is non-NA) and increments in those observations where x is
non-NA.

Cross-references
See also @cumnas (p. 796).

For the backward variant of this function, see @cumbobs (p. 780).

@cumprod Cumulative Statistics

Cumulative products of a series or of the elements of a matrix.


• Compute the cumulative product of the values in the series x from the start of the
workfile or sample s, up to the current observation:
Syntax: @cumprod(x[, s])
x: series, matrix, vector
s: (optional) sample string or object
Return: series, matrix, vector
798—Function Reference: C

• Compute the cumulative product of the elements of the matrix in vec order.
Syntax: @cumprod(m)
m: matrix, vector
Return: matrix, vector
t
yt   xj
j1

This function is panel aware.

Note that this function is prone to numeric overflow.

Examples
show @cumprod(x)

produces a linked series whose elements are the cumulative products of the elements in x.

Cross-references
See also @cumsum (p. 802), @cummean (p. 794), and @cumsumsq (p. 803).

For the backward variant of this function for series, see @cumbprod (p. 781).

@cumquantile Cumulative Statistics

Cumulative quantiles of a series.

Increasing samples calculation of the quantile value where approximately 100*q percent of
the data is less than or equal to the value,
Syntax: @cumquantile(x, q, [s])
x: series
q: number, series
s: (optional) sample string or object
Return: series
• The quantile value q must satisfy 0  q  1 .
• The cumulative quantiles are computed using the Rankit-Cleveland definition of the
empirical distribution function: for observation t , F  x t  r     r – 1  2   t .

To compute the cumulative quantile for observation t find r , the smallest rank such that:
q  F  xt  r  
@cumstdev—799

where the order statistics  x t  1 , x t  2 , , x t  t   represent data from the beginning of the
workfile or sample s, up to the current observation ( 1, t ), ordered from low to high. For
purposes of computing F , tied ranks are assumed to take the last tied value.

Then the quantile is computed as

 xt  1  if F  x t  1    q

y t    1 – d x t  r – k   dx  r  if F  x t  r – k    q  F  x t  r  

 NA if F  x t  t    q

where the interpolating constant is


q – F  xt  r – k  
d  ---------------------------------------------------
-
F  xt  r   – F  xt  r – k  

for k  0 the smallest integer where F  x t  r – k    q . In the leading case where there are no
tied x t  r  values, k  1 .
This function is panel aware.

Examples
show @cumquantile(@nrnd, 0.975)

generates a linked series that converges in probability to 1.95996... (the 97.5th percentile of
the standard normal distribution).

Cross-references
See also @cummedian (p. 794).

For the backward variant of this function, see @cumbquantile (p. 782).

@cumstdev Cumulative Statistics

Cumulative standard deviations (d.f. adjusted) of a series.

Equivalent to @cumstdevs.

Increasing samples calculation of the square root of the sample (d.f. adjusted) Pearson prod-
uct moment variance.
Syntax: @cumstdev(x, [s])
x: series
s: (optional) sample string or object
Return: series

The sample standard deviation is calculated for each observation t as


800—Function Reference: C

t
1 2
yt  -----------
t–1   xj – xt 
j1

where x t is the mean of x over the first t observations.

This function is panel aware.

Examples
series x = @nrnd
group g @cumstdev(x) @cumstdevs(x) @cumstdevp(x)
g.line

plots @cumstdev(x), @cumstdevs(x), and @cumstdevp(x) together. Note that


@cumstdev(x) and @cumstdevp(x) are equivalent. All three series converge in probability
to 1.

Cross-references
See also @cumstdevs (p. 801), @cumstdevp (p. 800), @cumvar (p. 803), @cumvars
(p. 805), and @cumvarp (p. 804).

For the backward cumulative variant of this function, see @cumbstdev (p. 783).

@cumstdevp Cumulative Statistics

Cumulative standard deviations (population – non-d.f. adjusted).

Increasing samples calculation of the square root of the population (non-d.f. adjusted) Pear-
son product moment variance.
Syntax: @cumstdevp(x, [s])
x: series
s: (optional) sample string or object
Return: series

The population standard deviation is calculated for each observation t as


t
1 2
yt  -----------
t–1   xj – xt 
j1

where x t is the mean of x over the first t observations.

This function is panel aware.


@cumstdevs—801

Examples
series x = @nrnd
group g @cumstdev(x) @cumstdevs(x) @cumstdevp(x)
g.line

plots @cumstdev(x), @cumstdevs(x), and @cumstdevp(x) together. Note that


@cumstdev(x) and @cumstdevp(x) are equivalent. All three series converge in probability
to 1.

Cross-references
See also @cumstdev (p. 799), @cumstdevs (p. 801), @cumvar (p. 803), @cumvars (p. 805),
and @cumvarp (p. 804).

For the backward variant of this function, see @cumbstdevp (p. 784).

@cumstdevs Cumulative Statistics

Cumulative sample standard deviations (sample – d.f. adjusted) of a series.

Increasing samples calculation of the square root of the sample (d.f. adjusted) Pearson prod-
uct moment variance.
Syntax: @cumstdevs(x, [s])
x: series
s: (optional) sample string or object
Return: series

The sample standard deviation is calculated for each observation t as


t
1 2
yt  -----------
t–1   xj – xt 
j1

where x t is the mean of x over the first t observations.

This function is panel aware.

Examples
series x = @nrnd
group g @cumstdev(x) @cumstdevs(x) @cumstdevp(x)
g.line

plots @cumstdev(x), @cumstdevs(x), and @cumstdevp(x) together. Note that


@cumstdev(x) and @cumstdevp(x) are equivalent. All three series converge in probability
to 1.
802—Function Reference: C

Cross-references
See also @cumstdev (p. 799), @cumstdevp (p. 800), @cumvar (p. 803), @cumvars (p. 805),
and @cumvarp (p. 804).

For the backward variant of this function, see @cumbstdevs (p. 785)

@cumsum Cumulative Statistics

Cumulative sums of a series or of the elements of a matrix.


• Compute the sum of the values in the series x from the start of the workfile or sample
s, up to the current observation:
Syntax: @cumsum(x[, s])
x: series
s: (optional) sample string or object
Return: series
• Compute the cumulative sum of the elements of the matrix in vec order.
Syntax: @cumsum(m)
m: matrix, vector
Return: matrix, vector

Compute the cumulative sum of the values in x from the start of the workfile or sample s, up
to the current observation:
t
yt   xj
j1

This function is panel aware.

Examples
series x = @cumsum(@nrnd)

generates a random walk process x with standard normal errors, initialized at a draw from
the standard normal distribution.

Cross-references
See also @cummean (p. 794), @cumsumsq (p. 803), and @cumprod (p. 797).

For the backward variant of this function for series, see @cumbsum (p. 786).
@cumvar—803

@cumsumsq Cumulative Statistics

Cumulative sums of squares of a series.

Increasing samples calculation of the sum of the squared values in x.


Syntax: @cumsumsq(x[, s])
x: series
s: (optional) sample string or object
Return: series

Compute the cumulative sum of the squared values in x from the start of the workfile or
sample s, up to the current observation:
t
2
yt   xj
j1

This function is panel aware.

Examples
series x = @cumsumsq(@nrnd) / (@trend + 1)

generates a random process x that converges in probability to 1.

Cross-references
See also @cumsum (p. 802), @cummean (p. 794), and @cumprod (p. 797).

For the backward variant of this function, see @cumbsumsq (p. 786).

@cumvar Cumulative Statistics

Cumulative variances (population – non-d.f. adjusted) of a series.

Equivalent to @cumvarp.

Increasing samples calculation of the population (non-d.f. adjusted) Pearson product


moment variance.
Syntax: @cumvar(x, [s])
x: series
s: (optional) sample string or object
Return: series

The population variance for each observation t is calculated as


804—Function Reference: C

t
1 2
y t  ---
t   xj – xt 
j1

where x t is the mean of x over the first t observations.

This function is panel aware.

Examples
series x = @nrnd
group g @cumvar(x) @cumvars(x) @cumvarp(x)
g.line

plots @cumvar(x), @cumvars(x), and @cumvarp(x) together. Note that @cumvar(x) and
@cumvarp(x) are equivalent. All three series converge in probability to 1.

Cross-references
See also @cumstdev (p. 799), @cumstdevs (p. 801), @cumstdevp (p. 800), @cumvars
(p. 805), and @cumvarp (p. 804).

For the backward variant of this function, see @cumbvar (p. 787).

@cumvarp Cumulative Statistics

Cumulative variance (population – non-d.f. adjusted) of a series.

Increasing samples calculation of the population (non-d.f. adjusted) Pearson product


moment variance.
Syntax: @cumvarp(x, [s])
x: series
s: (optional) sample string or object
Return: series

The population variance for each observation t is calculated as


t
1 2
y t  ---
t   xj – xt 
j1

where x t is the mean of x over the data first t observations.

This function is panel aware.

Examples
series x = @nrnd
group g @cumvar(x) @cumvars(x) @cumvarp(x)
@cumvars—805

g.line

plots @cumvar(x), @cumvars(x), and @cumvarp(x) together. Note that @cumvar(x) and
@cumvarp(x) are equivalent. All three series converge in probability to 1.

Cross-references
See also @cumstdev (p. 799), @cumstdevs (p. 801), @cumstdevp (p. 800), @cumvar
(p. 803), and @cumvars (p. 805).

For the backward variant of this function, see @cumbvarp (p. 788).

@cumvars Cumulative Statistics

Cumulative variances (sample – d.f. adjusted) of a series.

Increasing samples calculation of the sample (d.f. adjusted) Pearson product moment vari-
ance.
Syntax: @cumvars(x, [s])
x: series
s: (optional) sample string or object
Return: series

The sample variance for each observation t is calculated as


t
1 2
y t  -----------
t–1   xj – xt 
j1

where x t is the mean of x over the first t observations,.

This function is panel aware.

Examples
series x = @nrnd
group g @cumvar(x) @cumvars(x) @cumvarp(x)
g.line

plots @cumvar(x), @cumvars(x), and @cumvarp(x) together. Note that @cumvar(x) and
@cumvarp(x) are equivalent. All three series converge in probability to 1.

Cross-references
See also @cumstdev (p. 799), @cumstdevs (p. 801), @cumstdevp (p. 800), @cumvar
(p. 803), and @cumvarp (p. 804).

For the backward variant of this function, see @cumbvars (p. 789).
806—Function Reference: C

@cunif Element Functions

Uniform cumulative distribution.


Syntax: @cunif(x, a, b[, u])
x: number
a: number
b: number, b  a
u: (optional) number
Return: number

Computes the cumulative distribution function

 0 xa
 x – a
F  x, a, b    ----------------- axb
 b–a
 1 xb

If the optional argument u is non-zero, return the upper-tail value:

 1 xa
 b – x
G  x, a, b    ----------------- axb
 b–a
 0 xb

Examples
= @cunif(4, 1, 6)

returns 0.6.

Cross-references
See also @dunif (p. 849), @qunif (p. 1059), and @runif (p. 1100).

@cvalcount Matrix Column Statistics

Count of matching values in each column.


Syntax: @cvalcount(x, y)
x: data object
y: value or string
Return: vector
@cvarp—807

The number of elements in each column of x that match y. Note that numeric matches
require an exact match.

Examples
Let X be a matrix. Then
= @cvalcount(x, 2)

returns a vector containing the number of elements in each column of X that take the value
2.

Cross-references
See also @valcount (p. 1178).

@cvar Matrix Column Statistics

Variance (population) of each column of a matrix.


Syntax: @cvar(m)
m: matrix
Return: vector

Returns the column population variance.

Examples
= @cvar(mat)

returns a (column) vector whose i-th element is the population variance for the i-th column
of MAT.

Cross-references
See also @cstdev (p. 772), @cstdevs (p. 773), @cstdevp (p. 773), and @cvarp (p. 807).

@cvarp Matrix Column Statistics

Variance (population) of each column of a matrix.


Syntax: @cvarp(m)
m: matrix
Return: vector

Returns the column population variance.


808—Function Reference: C

Examples
= @cvarp(mat)

returns a (column) vector whose i-th element is the population variance for the i-th column
of MAT.

Cross-references
See also @cstdev (p. 772), @cstdevs (p. 773), @cstdevp (p. 773), and @cvar (p. 807).

@cvars Matrix Column Statistics

Variance (sample) of each column of a matrix.


Syntax: @cvars(m)
m: matrix
Return: vector

Returns the column sample variance.

Examples
= @cvars(mat)

returns a (column) vector whose i-th element is the sample variance for the i-th column of
MAT.

Cross-references
See also @cstdev (p. 772), @cstdevs (p. 773), @cstdevp (p. 773), @cvar (p. 807), and
@cvarp (p. 807).

@cweib Element Functions

Weibull cumulative distribution.


Syntax: @cweib(x, m, a[, u])
x: number, x  0
m: number, m  0
a: number, a  0
u: (optional) number
Return: number

Computes the cumulative distribution function


@cweib—809

 0 x0
F  x, m, a    a
(18.4)
 1 – exp  –  x  m   x0

If the optional argument u is non-zero, return the upper-tail value:

 1 x0
G  x, m, a    a
(18.5)
 exp  –  x  m   x0

Examples
= @cweib(@log(2), 1, 1)

returns 0.5.

Cross-references
See also @dweib (p. 855), @qweib (p. 1060), and @rweib (p. 1104).
810—Function Reference: C
Function Reference: D—811

Function Reference: D
d...........................Difference (time-series) functions for series (p. 812).
@datapath ............EViews data directory (p. 813).
@date ...................Date number of observation (p. 814).
@dateadd..............Date number after applying offset (p. 815).
@datediff ..............Difference between two date numbers (p. 817).
@dateceil..............Last possible date in a time period (p. 819).
@datefloor ............Earliest possible date in a time period (p. 820).
@datenext ............First possible date in the next time period (p. 821).
@datepart .............Extract part of a date number (p. 823).
@datestr ...............String representation of a date number (p. 824).
@dateval ..............Date number associated with a string representation of a date
(p. 825).
@day ....................Day of observation (p. 826).
@daycount ...........Number of days of week in observation (p. 827).
@dbeta .................Beta distribution probability density (p. 828).
@dbinom..............Binomial probability function (p. 828).
@dbname .............String containing the default database name (p. 829).
@dbvnorm............Bivariate normal probability density function (p. 829).
@dchisq ...............Chi-square probability density function (p. 830).
@dcumdn .............Difference of cumulative sum of negative (below threshold)
changes in a series (p. 831).
@dcumdp .............Difference of cumulative sum of positive (above threshold) changes
in a series (p. 832).
@dcumdz .............Difference of cumulative sum of zero (at threshold) changes in a
series (p. 833).
@demean .............Compute deviations from the mean of the series (p. 834).
@demeanby..........Compute deviations from the mean of the series by group (p. 835).
@det.....................Determinant of matrix (p. 835).
@detrend ..............Compute deviations from the trend of the series (p. 836).
@dexp ..................Exponential probability density function (p. 837).
@dextreme ...........Extreme value (Type I-minimum) distribution function (p. 837).
@dfdist .................F-distribution probability density function (p. 838).
@dgamma ............Gamma probability density function (p. 838).
@dged ..................Generalized error probability density function (p. 839).
@digamma ...........First derivative of the natural log gamma function (p. 839).
@diwish ...............Inverse Wishart probability density function (p. 840).
@dlaplace .............Laplace probability density function (p. 841).
812—Function Reference: D

dlog ..................... Difference functions for natural logarithm of a series (p. 842).
@dlogistic ............ Logistic probability density function (p. 843).
@dlognorm .......... Log normal probability density function (p. 843).
@dmvnorm .......... Multivariate normal probability density function (p. 844).
@dnegbin ............ Negative binomial probability function (p. 845).
@dnorm............... Standard normal probability density function (p. 845).
@dpareto ............. Pareto probability density function (p. 846).
@dpoisson ........... Poisson probability function (p. 846).
@dtdist ................ Student’s t probability density function (p. 847).
@dtoo .................. Observation number in the workfile associated with a date string
(p. 847).
@dunif................. Uniform probability density function (p. 849).
@duplic ............... Duplication matrix (p. 849).
@duplicinv .......... Inverse duplication matrix (p. 850).
@dupselem .......... Identifier for the observation within the set of duplicates (p. 851).
@dupsid .............. Identifier for the duplicates group for the observation (p. 852).
@dupsobs ............ Number of observations in the corresponding duplicates group
(p. 853).
@during............... Indicator of whether an observation is between two dates (p. 854)
@dweib ............... Weibull probability density function (p. 855).
@dwish ............... Wishart probably density function (p. 856).

d Series Utility

Difference (time-series) functions for series.


• First difference function for series.
Syntax: d(x)
x: series
Return: series

Computes  1 – L x  x – x  – 1  where L is the lag operator.


• n-th order difference function for series.
Syntax: d(x, n)
x: series
n: integer, series
Return: series
n
Computes  1 – L  x where L is the lag operator.
@datapath—813

If n is not an integer, the integer floor n will be used.


• n-th order difference function for series with an s-th seasonal difference.
Syntax: d(x, n, s)
x: series
n: integer
s: integer
Return: series
n s
Computes  1 – L   1 – L x where L is the lag operator.

If n or s are not integers, the integer floors n and s will be used.

These functions are panel aware.

Examples
The code below produces a graph of a random walk process and its first difference:
wfcreate u 1000
series y = 0
smpl @first+1 @last
series y = y(-1) + nrnd
smpl @all
group g y d(y)
g.line

The first line creates an unstructured workfile containing a thousand observations. Lines
two through five create the series y containing the realization of a random walk process ini-
tialized at 0. Lines six and seven graphs y and d(y) together.

Cross-references
See also dlog (p. 842).

@datapath Support Functions

Path of the current EViews data directory.


Syntax: @datapath
Return: string

Returns a string containing the location of the current EViews data directory.

Examples
If your current working directory is d:\data
814—Function Reference: D

%y = @datapath

assigns a string of the form “D:\DATA”.

Cross-references
See also @evpath (p. 878) and @temppath (p. 1145).

@date Workfile Functions

Date number of observation.


Syntax: @date
Return: series

Returns the date number associated with each observation in the workfile.

The date number associated with an observation is the first (smallest) date number corre-
sponding to the observation date interval.

Examples
series dt = @date

saves the date numbers into the series DT. The default display format for these numbers will
match the workfile frequency, but you may work with and display the series values as num-
bers.
alpha dts_1 = @datestr(@date,"yyyy:q")
alpha dts_2 = @strdate("yyyy:q")

Create two string series with the observation dates formatted in “yyyy:q” format.

Cross-references
See “Date Numbers,” on page 106 and “Date Formats” on page 106.

See also @enddate (p. 870), @datestr (p. 824) and @strdate (p. 1128).
@dateadd—815

@dateadd Element Functions | Date Functions

Date number after applying offset.


Syntax: @dateadd(d, offset, u[, f])
d: date number, series, vector
offset: integer, series, vector
u: time unit string
f: (optional) number
Return: date number, series, vector

Returns the date number given by d offset by offset time units as specified by the time unit
string u. The optional parameter f controls handling of business days.
• The valid time unit string values are: “A” or “Y” (annual), “S” (semi-annual), “Q”
(quarters), “MM” (months), “WW” (weeks), “DD” (days), “B” (business days), “HH”
(hours), “MI” (minutes), “SS” (seconds).
• When the time unit u is business days (“B”), the optional control flag parameter f
controls how a non-business day date number d is handled. When f is absent or equal
to zero, the date number d is automatically advanced to the next business day before
offset is applied. Otherwise, when f is non-zero automatic advancement is suppressed.
Consequently, when f is non-zero and offset is 0 the function returns the original date
number d (a non-business day).

Examples
Suppose that the value of d is 730088.0 (midnight, December 1, 1999).

Then we can add and subtract 10 days from the date by using the functions
@dateadd(730088.0, 10, "dd")
@dateadd(730088.0, -10, "dd")

which return 730098.0 (December 11, 1999) and (730078.0) (November 21, 1999). Note that
these results could have been obtained by taking the original numeric value plus or minus
10.

To add 5 weeks to the existing date, simply specify “WW” as the time unit string:
@dateadd(730088.0, 5, "ww")

returns 730123.0 (January 5, 2000).

To find the date 3 months prior to the existing date, specify “MM” as the time unit string:
@dateadd(730088.0, -3, "mm")
816—Function Reference: D

The function may usefully be combined with other date functions. To find the day of the
week 4 months from DD:
@datestr(@dateadd(dd, 4, "mm"), "Wdy")

Business day adjustments are slightly more complex. Suppose that the value of DD is
730091.0 (midnight, December 4, 1999), which is a Saturday:
730091.0

Then the previous business day, may be obtained by


@dateadd(dd, -1, "b")
@dateadd(dd, -1, "b", 1)

which both return 730090.0 (December 3, 1999), the preceding Friday.

A business day offset of 0 with a zero (or omitted) control flag f, automatically advances to
the next business day
@dateadd(dd, 0, "b")

returns 730093.0 (December 6, 1999), the following Monday.

A business day offset of 0 with a non-zero control flag f, does not advance from the original
day, so that
@dateadd(dd, 0, "b", 1)

returns 730091.0 (December 4, 1999), the original Saturday.

Automatic business day adjustments are performed prior to applying the offset parameter, so
that
@dateadd(dd, 1, "b")

returns 730094.0 (December 7, 1999), the following Tuesday, while


@dateadd(dd, 1, "b", 1)

returns 730093.0 (December 6, 1999), the following Monday.

If DSER is a series containing date numbers,


series dser1 = @dateadd(dser, 3, "mm")

produces the 3-month date number offsets associated for each observation for DSER in the
workfile sample. You may use “@date” in place of DSER to obtain results using the built-in
dates in the workfile structure.

If DVEC is an vector containing date numbers,


vector avec = @dateadd(dvec, 3, "mm")

produces the 3-month date number offsets for elements of the vector.
@datediff—817

Cross-references
See “Dates” on page 104 and “Date Formats” on page 106 for additional details on date
numbers and date format strings.

See also @datediff (p. 817) and @dateval (p. 825).

@datediff Element Functions | Date Functions

Difference between two date numbers.


Syntax: @datediff(d1, d2, u[, f])
d1: date number, series, vector
d2: date number, series, vector
u: time unit string
f: (optional) number
Return: date number, series, vector

Returns the difference between two date numbers d1 and d2, measured by time units speci-
fied by the time unit string u. The optional parameter f controls handling of business days.
• The valid time unit string values are: “A” or “Y” (annual), “S” (semi-annual), “Q”
(quarters), “MM” (months), “WW” (weeks), “DD” (days), “B” (business days), “HH”
(hours), “MI” (minutes), “SS” (seconds).
• When the time unit u is business days (“B”), the optional control flag parameter f
controls how a non-business day date number d is handled. When f is absent or equal
to zero, the date number d is automatically advanced to the next business day before
offset is applied. Otherwise, when f is non-zero automatic advancement is suppressed.
Consequently, when f is non-zero and offset is 0 the function returns the original date
number d (a non-business day).

Examples
Suppose d1 is 730088.0 (December 1, 1999) and d2 is 729754.0 (January 1, 1999). We may
define
scalar d1 = 730088.0
scalar d2 = 729754.0

The two commands


@datediff(730088.0, 729754.0, "dd")
@datediff(d1, d2, "dd")

return 334 for the number of days between the two dates. Note that this is result is simply
the difference between the two numbers.
818—Function Reference: D

The following expressions calculate differences in months and weeks:


@datediff(730088.0, 729754.0, "mm")
@datediff(730088.0, 729754.0, "ww")

and
@datediff(d1, d2, "mm")
@datediff(d1, d2, "22")

return 11 and 47 for the number of months and weeks between the dates.

Business day computations are slightly more complex. Suppose that d1 is 730094.0 (mid-
night, December 7, 1999), which is a Tuesday, and d2 is 730091.0 (midnight, December 4,
1999), which is the preceding Saturday:
scalar d1 = 730094.0
scalar d2 = 730091.0
@datediff(d1, d2, "b")

returns 1 for the number of business days between the two dates since the absence of the
control flag means that the d2 date automatically advances to the next business day
@datediff(d1, d2, "b", 1)

returns 2 for the number of business days between the two dates since, control flag argu-
ment of 1 means that the d2 date does not automatically advance to the next (Monday) busi-
ness day.

If DSER1 and DSER2 are series containing date numbers,


series dser3 = @datediff(dser1, ders2, "mm")

compute the month differences for each observation for DSER1 and DSER2 in the workfile
sample.

If DVEC1 and DVEC2 are vectors containing date numbers,


vector dvecdiff = @datediff(dvec1, dvec2, "mm")

compute the month differences for all elements of the vectors.

Cross-references
See “Dates” on page 104 and “Date Formats” on page 106 for additional details on date
numbers and date format strings.

See also @dateadd (p. 815) and @dateval (p. 825).


@dateceil—819

@dateceil Element Functions | Date Functions

Last possible date in a time period.


Syntax: @dateceil(d, u[, step])
d: date number, series, vector
u: time unit string
step: (optional) integer, series, vector
Return: date number, series, vector

Finds the last possible date number associated with d in the regular frequency defined by
the given time unit u and optional step integer step. The regular frequency is defined relative
to the basedate of midnight, January 2001.
• The valid time unit string values are: “A” or “Y” (annual), “S” (semi-annual), “Q”
(quarters), “MM” (months), “WW” (weeks), “DD” (days), “B” (business days), “HH”
(hours), “MI” (minutes), “SS” (seconds).
• If step is omitted, the frequency will use a step of 1, so that by default, @dateceil
will find the end of the period defined by the time unit.

Examples
Suppose that d is 730110.8 (7 PM, December 23, 1999).

Then the command


@dateceil(730110.8, "dd")

gives the last date number associated with the end of December 23, 1999, yielding
730110.999 (11:59:59.999... PM, December 23, 1999).

Similarly, the command,


@dateceil(730110.8, "mm")

gives the date number associated with the end of month of December 1999 (11:59:59.999...
PM, December 31, 1999) giving 730118.999.

The commands
@dateceil(730110.8, "hh", 3)
@dateceil(730110.8, "hh", 6)

return 730110.874999 (8:59:59.999... PM, December 23, 1999), and 730110.999


(11:59:59.999... PM, December 23, 1999), which are the last date numbers for 3 and 6 hour
regular frequencies anchored at midnight, January 1, 2001.
820—Function Reference: D

If DSER is a series containing date numbers,


series dser1 = @dateceil(dser, "mm")

gives the date number of the end of the month for each observation in DSER in the workfile
sample. You may use “@date” in place of DSER to obtain results using the built-in dates in
the workfile structure.

If DVEC is a vector containing date numbers,


vector avec = @dateceil(dvec, "y")

gives the last date number in the year for each element of the vector.

Cross-references
See “Dates” on page 104 and “Date Formats” on page 106 for additional details on date
numbers and date format strings.

See also @datefloor (p. 820), @datenext (p. 821), and @dateval (p. 825).

@datefloor Element Functions | Date Functions

First possible date in a time period.


Syntax: @datefloor(d, u[, step])
d: date number, series, vector
u: time unit string
step: (optional) integer, series, vector
Return: date number, series, vector

Finds the first possible date number associated with d in the regular frequency defined by
the given time unit u and optional step integer step. The regular frequency is defined relative
to the basedate of midnight, January 2001.
• The valid time unit string values are: “A” or “Y” (annual), “S” (semi-annual), “Q”
(quarters), “MM” (months), “WW” (weeks), “DD” (days), “B” (business days), “HH”
(hours), “MI” (minutes), “SS” (seconds).
• If step is omitted, the frequency will use a step of 1, so that by default, @dateceil
will find the end of the period defined by the time unit.

Examples
Suppose that d is 730110.8 (7 PM, December 23, 1999).

Then the command


@datefloor(730110.8, "dd")
@datenext—821

gives the first date number associated with the end of December 23, 1999, yielding 730110.0
(midnight, December 23, 1999).

Similarly, the command


@datefloor(730110.8, "mm")

returns 730088.0 (midnight, December 1, 1999), the date number for the beginning of the
associated with 730110.8.

The commands
@datefloor(730110.8, "hh", 6)
@datefloor(730110.8, "hh", 12)

return 730110.75 (6 PM, December 23, 1999), and 730110.5 (Noon, December 23, 1999),
which are the earliest date numbers for 6 and 12 hour regular frequencies anchored at Mid-
night, January 1, 2001.

If DSER is a series containing date numbers,


series dser1 = @datefloor(dser, "mm")

gives the date number of the beginning of the month for each observation in DSER in the
workfile sample. You may use “@date” in place of DSER to obtain results using the built-in
dates in the workfile structure.

If DVEC is a vector containing date numbers,


vector avec = @datefloor(dvec, "y")

gives the first date number in the year for each element of the vector.

Cross-references
See “Dates” on page 104 and “Date Formats” on page 106 for additional details on date
numbers and date format strings.

See also @dateceil (p. 819), @datenext (p. 821), and @dateval (p. 825).

@datenext Element Functions | Date Functions

First possible date in next time period.


Syntax: @datenext(d, u[, step])
d: date number, series, vector
u: time unit string
step: (optional) integer, series, vector
Return: date number, series, vector
822—Function Reference: D

Finds the first possible date number in the next regular frequency period following d,
defined by the given time unit u and optional step integer step. The regular frequency is
defined relative to the basedate of midnight, January 2001.
• The valid time unit string values are: “A” or “Y” (annual), “S” (semi-annual), “Q”
(quarters), “MM” (months), “WW” (weeks), “DD” (days), “B” (business days), “HH”
(hours), “MI” (minutes), “SS” (seconds).
• If step is omitted, the frequency will use a step of 1, so that by default, @datenext
will find the end of the period defined by the time unit.

Examples
Suppose that date1 is 730110.8 (7 PM, December 23, 1999).

Then the commands


@datenext(730110.8, "dd")
@datenext(730110.8, "mm")

yield 730111.0 (midnight, December 24, 1999) and 730119.0 (midnight, January 1, 2000), the
date numbers for the beginning of the day and month following the date number 730110.8,
respectively.

Similarly,
@datenext(730110.8, "hh", 3)
@datenext(730110.8, "hh", 6)

return 730110.875 (9 PM, December 23, 1999), and 730111 (midnight, December 24, 1999),
which are the earliest date numbers for the subsequent 3 and 6 hour regular frequencies
anchored at midnight, January 1, 2001.

If DSER is a series containing date numbers from the workfile structure


series dser1 = @datenext(dser, "mm")

gives the date number of the beginning of the next month for each observation in DSER in
the workfile sample. You may use “@date” in place of DSER to obtain results using the
built-in dates in the workfile structure.

If DVEC is a vector containing date numbers,


vector avec = @datenext(dvec, "y")

gives the first date number in the next year for each element of the vector.

Cross-references
See also @dateceil (p. 819), @datefloor (p. 820), and @dateval (p. 825).
@datepart—823

@datepart Element Functions | Date Functions

Extract part of a date number.


Syntax: @datepart(d, fmt)
d: date number, series, vector
fmt: date format string
Return: number, series, vector

Returns a number representing part of a date, using a date number corresponding to the date
and a fmt, where fmt is a component of a date format string.

Examples
Consider the d date number value 730110.5 (noon, December 23, 1999).

The values for


@datepart(730110.5, "dd")
@datepart(730110.5, "w")
@datepart(730110.5, "ww")
@datepart(730110.5, "mm")
@datepart(730110.5, "yy")

are 23 (day of the month), 1 (day of the week), 52 (week in the year), 12 (month in the
year), and 99 (year), respectively).

If DSER is a series containing date numbers,


series dser1 = @datepart(dser, "mm")

gives the month of the year given by each observation in DSER in the workfile sample. You
may use “@date” in place of DSER to obtain results using the built-in dates in the workfile
structure.

If AVEC is a vector containing date numbers,


vector avec1 = @datenext(avec, "y")

returns the year for each element of the vector.

Cross-references
See “Dates” on page 104 and “Date Formats” on page 106 for additional details on date
numbers and date format strings.
824—Function Reference: D

@datestr Element Functions | Date Functions

String representation of a date number.


Syntax: @datestr(d[, fmt])
d: date number, series, vector
fmt: (optional) date format string
Return: string, alpha, svector

Convert the numeric date value, d, into a string representation of a date using the optional
format string fmt. Date format syntax is outlined in “Date Formats” on page 106.

If a fmt is not provided, EViews will use the global default settings for the Month/Day order
in dates to determine the ordering of days and months in the string.

Next, EViews examines the date values to be translated and looks for relevant time-of-day
information. If there is relevant time-of-day information, EViews will extend the date format
accordingly by adding relevant hours, minutes, and seconds information, in that order.
Thus, if days are favored in the global default ordering, and relevant hours (but not minutes
and seconds) information is present, EViews will use
"dd/mm/yyyy hh"

while if hours-minutes are present, the default format will be


"dd/mm/yyyy hh:mi"

and so forth.

Examples
Consider the d date number value 730088 (midnight, December 1, 1999).

Then
@datestr(730088, "mm/dd/yy")

will return “12/1/99”,


@datestr(730088, "DD/mm/yyyy")

will return “01/12/1999”, and


@datestr(730088, "Month dd, yyyy")

will return “December 1, 1999”, and


@datestr(730088, "w")

will produce the string “3”, representing the weekday number for December 1, 1999.
@dateval—825

You may use text to delimit the date format components,


@datestr(730088, "yyyy:q")
@datestr(730088, "yyyy[q]q")

produces “1999:4” and “1999q4”. Note the use of the square brackets to pass through the lit-
eral “q” string to the string output. If the workfile is quarterly, then
@datestr(730088, "yyyy[q]q")

also returns “1999q4” as the “f” will return the frequency delimiter from the active workfile
page.

If DSER is a series containing date numbers,


alpha aser1 = @datestr(dser, "Month dd, yyyy")

produces the formatted date string for each observation in DSER in the workfile sample.

If DVEC is a vector containing date numbers,


svector avec = @datestr(dvec, "DD/mm/yyyy")

returns a svector containing strings with the day, month, and year, corresponding to each
element of the DVEC vector.

Cross-references
See “Dates” on page 104 and “Date Formats” on page 106 for additional details on date
numbers and date format strings.

See @strdate (p. 1128) to obtain workfile date strings. See also @dateval (p. 825) for con-
verting date strings to date numbers.

@dateval Element Functions | Date Functions

Convert the string representation of a date into a date number.


Syntax: @dateval(str1[, fmt])
str1: string, alpha, svector
fmt: (optional) date format string
Return: date number, series, vector

Returns the date number associated with the string representation of a date, str. Interpreta-
tion of the string may be controlled of using the optional format string fmt.

Examples
@dateval("12/1/1999", "mm/dd/yyyy")
826—Function Reference: D

contains the date number (730088) for December 1, 1999. The format indicates that the
string represents a one or two-digit month identifier, a “/” separator, a one or two-digit day
identifier, a “/” separator, and a 4-digit year identifier.
@dateval("12/1/1999", "dd/mm/yyyy")

contains the date number (729765) for January 12, 1999. The format reverses the month and
day identifiers used above.

If ALPHA1 is an alpha series, the command


series ser1 = @dateval(alpha1, "yyyy-MM-DD HH:mi:ss")

fills DSER with date numbers associated with the ISO 8601 representation of the string dates
for each observation in the workfile sample. Here, we have used the capitalized forms of
“MM”, “DD”, and “HH” to ensure that we interpret the required leading zeros.

If AVEC1 is an svector, the commands


svector vec1 = @dateval(avec1, "yyyy-Month-dd")

fills DVEC with the date numbers associated with the strings in AVEC1, interpreted as a four-
digit year, followed by the full name of the month (with first letter capitalized), and the one
or two-digit day identifier, all separated by dashes.

Cross-references
See “Dates” on page 104 and “Date Formats” on page 106 for additional details on date
numbers and date format strings.

See @datestr (p. 824) for converting date numbers to date strings, and @strdate (p. 1128)
for obtaining strings for workfile dates.

@day Workfile Functions

Day of observation.
Syntax: @day
Return: series

Returns the day of the month (1-31) associated with each observation in the workfile.
• If the workfile is of lower than daily frequency, all observations will be set to 1.
• If the workfile is undated, observations will be set to -1.

Examples
series dt = @day
@daycount—827

saves the days of the month into the series DT.


The command
smpl if @day > 29
sets the sample to only use days 30 and 31 of months.

Cross-references
See also @hour (p. 910), @hourf (p. 910), @minute (p. 978), @month (p. 983), @quarter
(p. 1059), @seas (p. 1109), @second (p. 1109), @weekday (p. 1192), and @year (p. 1223).

@daycount Workfile Functions

Number of calendar days in observation.


Syntax: @daycount(d)
d: string, alpha
Return: series

Returns the number of calendar days within each observation of the workfile.

The optional d argument lets you specify an individual day or range of days of the week to
count (e.g., “Mon”, “Tues-Thurs”, or “Fri Sat”).
• If only one weekday is provided, @daycount returns the number of times that partic-
ular weekday occurs within the observation.
• If two weekdays are provided, @daycount returns the number of times that any week-
day between the two weekdays (inclusive) occurs within the observation.

If the workfile is undated, the function with return NAs.

Examples
series modays = @daycount("Mon")

creates a series with the number of Mondays in each observation.


series wkdays = @daycount(Mon Fri)

fills WKDAYS with the number of weekdays, while


series wenddays = @daycount("Sat Sun")

counts the number of weekend days in each observation.


workfile m 2020 2022
smpl if @daycount("Sat") > 4

creates a monthly workfile, and sets the sample to those months with 5 Saturdays.
828—Function Reference: D

Cross-references
See also @weekday (p. 1192).

@dbeta Element Functions

Beta distribution probability density.


Syntax: @dbeta(x, a, b)
x: number
a: number, a  0
b: number, b  0
Return: number

Evaluates the probability density function,


a–1 b–1
x 1 – x
f  x a, b   -------------------------------------- 0x1
B  a, b 
and 0 elsewhere, where B is the beta function
1
a–1 b–1 G  a G  b 
B  a, b   t 1 – t dt  ------------------------
Ga  b
0

Examples
= @dbeta(0.5, 1, 2)

returns 1.

Cross-references
See also @cbeta (p. 734), @qbeta (p. 1045), and @rbeta (p. 1067).

@dbinom Element Functions

Binomial distribution probability.


Syntax: @dbinom(x, n, p)
x: number
n: integer, n  0
p: number, 0  p  1
Return: number

Evaluates the probability function,


@dbvnorm—829

 n x
p  x, n, p      p  1 – p 
n–x
x  0, 1, , n
x 

and 0 elsewhere.

Examples
= @dbinom(2, 5, 0.5)

returns 0.3125.

Cross-references
See also @cbinom (p. 735), @qbinom (p. 1046), and @rbinom (p. 1067).

@dbname Support Functions

Default database name.


Syntax: @dbname
Return: string

Returns a string containing the name of the current default database.

Examples
string dbname = @dbname

creates a string variable with the default database name.

Cross-references
See also @pagename (p. 1029), @wfname (p. 1198), and @wfpath (p. 1198).

@dbvnorm Element Functions

Bivariate normal probability density.


Syntax: @dbvnorm(x, y, r)
x: number
y: number
p: number, 0  r  1
Return: number

Computes the bivariate normal density with 0 mean, unit variances, and correlation r:
830—Function Reference: D

1 1
f  s, t r   -------------------------- exp  – ----------------------  x – 2rxy  y 
2 2
 2 
2p 1 – r
2 21 – r 

Examples
= @dbvnorm(0, 0, 0.5)

returns 0.18377....

Cross-references
See also @cbvnorm (p. 735).

@dchisq Element Functions

Chi-square probability density.


Syntax: @dchisq(x, v)
x: number
v: number, v  0
Return: number

Evaluates the probability density function,


1 v  2 – 1 –x  2
f  x v   ------------------------------ x e
v2
2 Gv  2
for x  0 or 0 elsewhere.

Examples
= @dchisq(100, 100)

returns 0.02816....

Cross-references
See also @cchisq (p. 736), @chisq (p. 742), @qchisq (p. 1047), and @rchisq (p. 1068).
@dcumdn—831

@dcumdn Cumulative Statistics

Difference of the cumulative process of negative (below threshold) changes.

Compute the difference of the partial sum process of negative (below the threshold y)
changes in the series x beginning in the specified date.
Syntax: @dcumdn(x, d[, y, s])
x: series
d: string
y: (optional) number
s: (optional) sample string or object
Return: series

Consider the partial sum decomposition of a variable z t given a initial value z 0 as


+ – 0 + – 0
z t  z 0  z t  z t  z t where z t , z t , and z t are the partial sum processes of the differ-
ences for positive, negative, and zero changes in z t relative to the threshold y:
t
+
zt   z s  I  z s  y 
s1
t

zt   z s  I  z s  y 
s1
t
0
zt   z s  I  z s  y 
s1

The function returns the negative accumulation z t  z t  I  z s  y  for the current or
specified sample.
• The date d string specification determines t  1 .
• Values for dates prior to d will be NAs.
• The optional y argument specifies the threshold value. By default y  0 .

This function is panel aware.

Examples
The code below produces a graph of @cumdn and @dcumdn applied on the sine wave x.
wfcreate u 50
series x = @sin(@pi*@trend/4)
group g @cumdn(x,1) @dcumdn(x,1)
g.line
832—Function Reference: D

Cross-references
See also @cumdp (p. 791), @cumdn (p. 790), @cumdz (p. 792), @dcumdp (p. 832), and
@dcumdz (p. 833).

@dcumdp Cumulative Statistics

Difference of the cumulative process of positive (above threshold) changes.

Compute the difference of the partial sum process of positive (above the threshold y)
changes in the series x beginning in the specified date.
Syntax: @dcumdp(x, d[, y, s])
x: series
d: string
y: (optional) number
s: (optional) sample string or object
Return: series

Consider the partial sum decomposition of a variable z t given a initial value z 0 as


+ – 0 + – 0
z t  z 0  z t  z t  z t where z t , z t , and z t are the partial sum processes of the differ-
ences for positive, negative, and zero changes in z t relative to the threshold y:
t
+
zt   z s  I  z s  y 
s1
t

zt   z s  I  z s  y 
s1
t
0
zt   z s  I  z s  y 
s1
+
The function returns the positive accumulation z t  z t  I  z s  y  for the current or
specified sample.
• The date d string specification determines t  1 .
• Values for dates prior to d will be NAs.
• The optional y argument specifies the threshold value. By default y  0 .

This function is panel aware.

Examples
The code below produces a graph of @cumdp and @dcumdp applied on the sine wave x.
@dcumdz—833

wfcreate u 50
series x = @sin(@pi*@trend/4)
group g @cumdp(x,1) @dcumdp(x,1)
g.line

Cross-references
See also @cumdp (p. 791), @cumdn (p. 790), @cumdz (p. 792), @dcumdn (p. 831), and
@dcumdz (p. 833).

@dcumdz Cumulative Statistics

Difference of the cumulative process of zero (at threshold) changes.

Compute the difference of the partial sum process of zero (at the threshold y) changes in the
series x beginning in the specified date.
Syntax: @dcumdz(x, d[, y, s])
x: series
d: string
y: (optional) number
s: (optional) sample string or object
Return: series

Consider the partial sum decomposition of a variable z t given a initial value z 0 as


+ – 0 + – 0
z t  z 0  z t  z t  z t where z t , z t , and z t are the partial sum processes of the differ-
ences for positive, negative, and zero changes in z t relative to the threshold y:
t
+
zt   z s  I  z s  y 
s1
t

zt   z s  I  z s  y 
s1
t
0
zt   z s  I  z s  y 
s1
0
The function returns the zero accumulation z t  z t  I  z s  y  for the current or
specified sample.
• The date d string specification determines t  1 .
• Values for dates prior to d will be NAs.
• The optional y argument specifies the threshold value. By default y  0 .
834—Function Reference: D

This function is panel aware.

Examples
show @dcumdz(x, 2001, 1)

produces a linked series of @dcumdz applied to x where the starting date is 2001 and the
threshold value is set to 1.

Cross-references
See also @cumdp (p. 791), @cumdn (p. 790), @cumdz (p. 792), @dcumdp (p. 832), and
@dcumdn (p. 831).

@demean Observation Functions | Matrix Transformation

Compute deviations from the mean of the series.


Syntax: @demean(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning
result to a series
Return: series, vector, matrix

Returns a copy of x after subtracting off the mean.

For series calculations, EViews will use the current or specified workfile sample.

This function is panel aware.

Examples
The code below produces a graph of a series and its demeaned form:
wfcreate m 2000 2020
series y = 10 + nrnd
group g y @demean(y)
g.line

The first line creates a monthly workfile starting in January 2000 and ending in December
2020. The second line generates a series y equal to 10 plus normal error. The last two lines
graphs y and @demean(y) together.

Cross-references
See also @demeanby (p. 835) and @detrend (p. 836).
@det—835

@demeanby Observation Functions

Compute deviations of the mean of series by group.


Syntax: @demeanby(x, g[, s])
x: series
g: series
s: (optional) sample string or object
Return: series

Returns a copy of x after subtracting off group means, where groups are defined by the series or
vector g.

EViews will use the current or specified workfile sample.

This function is panel aware.

Examples
The code below produces a graph of a series and its demeaned-by-group form:
wfcreate m 2000 2020
series y = @month + nrnd
group g y @demeanby(y, @month)
g.line

The first line creates a monthly workfile starting in January 2000 and ending in December
2020. The second line generates a series y equal to the month of the year plus normal error.
The last two lines graphs y and @demeanby(y, @month) together.

Cross-references
See also @demean (p. 834) and @detrend (p. 836).

@det Matrix Algebra

Determinant of matrix.
Syntax: @det(m)
m: matrix, sym
Return: number

Calculate the determinant of the square matrix or sym, m.

The determinant is nonzero for a nonsingular matrix and 0 for a singular matrix.
836—Function Reference: D

Examples
matrix m1 = @mnrnd(4, 4)
scalar sc1 = @det(m1)

computes the determinant of the matrix M1.


sym s1 = @inner(m1)
= @det(s1)

returns the determinant of the symmetric matrix S1.

Cross-references
See also @eigenvalues (p. 864), @rank (p. 1063), and @trace (p. 1147).

@detrend Observation Functions

Compute deviations from the trend of a series.


Syntax: @detrend(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning
result to a series
Return: series, vector, matrix

Returns the residuals of an OLS regression of the data versus an intercept and an implicit
time trend.

For series calculations, EViews will use the current or specified workfile sample.

This function is panel aware.

Examples
The code below produces a graph of a series and its detrended form:
wfcreate m 2000 2020
series y = @trend + nrnd
group g y @detrend(y)
g.line

The first line creates a monthly workfile starting in January 2000 and ending in December
2020. The second line generates a series y equal to trend plus normal error. The last two
lines graphs y and @detrend(y) together.

Cross-references
See also @demean (p. 834).
@dextreme—837

@dexp Element Functions

Exponential probability density.


Syntax: @dexp(x, m)
x: number
m: number, m  0
Return: number

Evaluates the probability density function,

 0 x0

f  x, m    1 – x  m
 ----e x0
m

Examples
= @dexp(@log(2), 1)

returns 0.5.

Cross-references
See also @cexp (p. 738), @qexp (p. 1047), and @rexp (p. 1072).

@dextreme Element Functions

Extreme value (Type I-minimum) probability density.


Syntax: @dextreme(x)
x: number
Return: number

Evaluates the probability density function,


x
f  x   exp  x – e 

Examples
= @dextreme(1)

returns 0.17937....

Cross-references
See also @cextreme (p. 739), @qextreme (p. 1048), and @rextreme (p. 1072).
838—Function Reference: D

@dfdist Element Functions

F-distribution probability density.


Syntax: @dfdist(x, v 1 , v 2 )
x: number
v1 : number, v 1  0
v2 : number, v 2  0
Return: number

Evaluates the probability density function,


v 2 v 2
v 11 v 22 v – 2  2 – v  v   2
f  x v 1, v 2   -------------------------------------
-x 1  v2  v1 x  1 2
B  v 1  2, v 2  2 

for x  0 and 0 otherwise, where B is the beta function


1 a–1 b–1 G  a G  b 
B  a, b   0 t 1 – t dt  ------------------------
Ga  b
Note that the functions allow for fractional degrees of freedom parameters v 1 and v 2 .

Examples
= @dfdist(1, 2, 2)

returns 0.25.

Cross-references
See also @cfdist (p. 739), @fdist (p. 882), @qfdist (p. 1048), and @rfdist (p. 1073).

@dgamma Element Functions

Gamma probability density.


Syntax: @dgamma(x, b, r)
x: number
b: number, b  0
r: number, r  0
Return: number

Evaluates the probability density function,


–r r – 1 –x  b
b x e
f  x b, r   --------------------------------
Gr
@digamma—839

for x  0 and 0 elsewhere.

Examples
= @dgamma(2, 4, 1)

returns 0.15163....

Cross-references
See also @cgamma (p. 741), @qgamma (p. 1050), and @rgamma (p. 1074).

@dged Element Functions

Generalized error probability density.


Syntax: @dged(x, v)
x: number
r: number, r  0
Return: number

Evaluates the probability density function,


3 12  G  3---   
r2
r G  ---  
r   r   r  
f  x, r   ------------------------- exp  – x  -------------- 
32
2G  --- 
1   G  1---   
r     r  

Examples
= @dged(0, 2)

returns 0.39894....

Cross-references
See also @cged (p. 742), @qged (p. 1050), and @rged (p. 1074).

@digamma Element Functions

First derivative of the natural log gamma function.


Syntax: @digamma(x)
x: number
Return: number

Computes the derivative of the log of the gamma function:


840—Function Reference: D

d log G  x  1 dG  x 
w  x   -----------------------  ----------- ---------------
dx G  x  dx
for x  0 .

Examples
= @digamma(1)

returns -0.57721....

Cross-references
See also @gammalog (p. 894), @trigamma (p. 1152), and @psi (p. 1043).

@diwish Element Functions

Inverse Wishart probability density.


Syntax: @diwish(X, S, n)
@diwishc(X, S, n)
@diwishi(X, S, n)
@diwishic(X, S, n)
X: sym, p  p
S: sym, matrix, p  p
n: number, n  p – 1
Return: number
–1
Evaluate the inverse Wishart distribution W  W, n  density function for sym values of X,
and W .

The inverse Wishart density is given by


n
---
2
W
f  X W, n   ----------------------------------------------------------------------
–1
-
np n  p  1- tr  WX 
------ ---------------------- -------------------------
n
G p  --- e
2 2 2
2 X
 2

where X and W are symmetric p  p matrices, and n  p – 1 .

There are four different forms of the density evaluation function, corresponding to different
ways of specifying S . The forms are distinguished by different suffixes that are applied to
the base “@dwish” command and how they change the interpretation of the S matrix argu-
ment:
@dlaplace—841

@diwish “” Supply W .
@diwishc “c” Supply the Cholesky decomposition of W .
This form is more efficient when performing multiple
draws from the same distribution (compute the Chole-
sky once, but sample many times).
–1
@diwishi “i” Supply W .
This form is more efficient than explicitly inverting
–1
W to supply W .
–1
@diwishic “ic” Supply the Cholesky decomposition of W .
This form combines the efficiencies of the Cholesky
and inverse forms.

–1
Note that if X is an inverse Wishart random variable, then X follows a Wishart distribu-
tion:
–1 –1 –1
X  W p  W, n   X  Wp  W , n 

Examples
= @diwish(@identity(3), @identity(3), 5)

returns 0.00018....

Cross-references
See also @dwish (p. 856), @rwish (p. 1104), and @riwish (p. 1079).

@dlaplace Element Functions

Laplace probability density.


Syntax: @dlaplace(x)
x: number
Return: number

Evaluates the probability density function,


1 –x
f  x   --- e
2

Examples
Cross-references
= @dlaplace(@log(2))

returns 0.25.
842—Function Reference: D

See also @claplace (p. 747), @qlaplace (p. 1051), and @rlaplace (p. 1080).

dlog Series Utility

Difference functions for natural logarithm of series.


• First difference function for natural logarithm of the series.
Syntax: dlog(x)
x: series

Computes  1 – L  log  x   log  x  – log  x  – 1   where L is the lag operator.


• n-th order difference function for natural logarithm of series.
Syntax: dlog(x, n)
x: series
n: integer, series
Return: series
n
Computes  1 – L  log  x  for integer n  0 where L is the lag operator.

If n is not an integer, the integer floor n will be used.


• n-th order difference function for natural logarithm of series with an s-th seasonal
difference.
Syntax: dlog(x, n, s)
x: series
n: integer, series
s: integer, series
Return: series
n s
Computes  1 – L   1 – L  log  x  for integer n, s  0 where L is the lag operator.

If n or s are not integers, the integer floors n and s will be used.

These functions are panel aware.

Examples
show dlog(y,2)

is equivalent to d(log(y),2), the 2nd-order difference of the log of the


series y.

Cross-references
See also d (p. 812).
@dlognorm—843

@dlogistic Element Functions

Logistic probability density.


Syntax: @dlogistic(x)
x: number
Return: number

Evaluates the probability density function,


–x
e
f  x   ------------------------
–x 2
1  e 

Examples
= @dlogistic(0)

returns 0.25.

Cross-references
See also @clogistic (p. 748), @qlogistic (p. 1052), and @rlogistic (p. 1081).

@dlognorm Element Functions

Log normal probability density.


Syntax: @dged(x, m, s)
x: number
m: number, m  0
s: number, s  0
Return: number

Evaluates the probability density function,


1 2 2
f  x, m, s   ------------------- exp  –  log x – m    2s  
2
x 2ps
for x  0 and 0 otherwise.

Examples
= @dlognorm(1, 0, 2)

returns 0.19947....
844—Function Reference: D

Cross-references
See also @clognorm (p. 749), @qlognorm (p. 1052), and @rlognorm (p. 1082).

@dmvnorm Element Functions

Multivariate normal probability density.


Syntax: @dmvnorm(x, S)
@dmvnormc(x, S)
@dmvnormi(x, S)
@dmvnormic(x, S)
x: vector
S: sym, matrix
Return: number

Evaluate the multivariate normal N  0, S  density function for vector values of x, and sym
S.
The mean zero multivariate normal density is given by
– --1-
1
exp  – ---  xS x 
2 –1
f  x S   2pS
 2 

There are four different forms of the density evaluation function, corresponding to different
ways of specifying S . The forms are distinguished by different suffixes that are applied to
the base “@dmvnorm” command and how they change the interpretation of the S matrix
argument:
@dmvnorm “” Supply S .
@dmvnormc “c” Supply the Cholesky decomposition of S .
This form is more efficient when performing multiple
draws from the same distribution (compute the Chole-
sky once, but sample many times).
–1
@dmvnormi “i” Supply S .
This form is more efficient than explicitly inverting
–1
S to supply S .
–1
@dmvnormic “ic” Supply the Cholesky decomposition of S .
This form combines the efficiencies of the Cholesky
and inverse forms.

Examples
= @dmvnorm(@zeros(3), @identity(3))
@dnorm—845

returns 0.06349....

Cross-references
See also @rmvnorm (p. 1085).

@dnegbin Element Functions

Negative binomial distribution probability.


Syntax: @dnegbin(x, n, p)
x: number
n: number, n  0
p: number, 0  p  1
Return: number

Evaluates the probability function,

 Gx  n x n
 ----------------------------------p  1 – p  x  0, 1, 
p  x, n, p    G  x  1 G  n 
 0 otherwise

Examples
= @dnegbin(9, 10, 0.5)

returns 0.09273....

Cross-references
See also @cnegbin (p. 753), @qnegbin (p. 1053), and @rnegbin (p. 1087).

@dnorm Element Functions

Standard normal probability density.


Syntax: @dnorm(x)
x: number
Return: number

Evaluates the probability density function,


–1  2 2
f  x    2p  exp  – x  2 

Examples
= @dnorm(0)
846—Function Reference: D

returns 0.39894....

Cross-references
See also @cnorm (p. 753), @logcnorm (p. 950), @qnorm (p. 1054), and @rnorm (p. 1087).

@dpareto Element Functions

Pareto probability density.


Syntax: @dpareto(x, k, a)
x: number
k: number, k  0
a: number, a  0
Return: number

Evaluates the probability density function,

 0 xk
f  x, k, a    a a1
  ak   x xk

Examples
= @dpareto(2, 1, 2)

returns 0.25.

Cross-references
See also @cpareto (p. 769), @qpareto (p. 1054), and @rpareto (p. 1092).

@dpoisson Element Functions

Poisson distribution probability.


Syntax: @dpoisson(x, m)
x: number
m: number, m  0
Return: number

Evaluates the probability function,

 x –m x  0, 1, , n, 
p  x, m    m e  x!
 0 otherwise
@dtoo—847

Examples
= @dpoisson(10, 10)

returns 0.12511....

Cross-references
See also @cpoisson (p. 770), @qpoisson (p. 1055), and @rpoisson (p. 1092).

@dtdist Element Functions

Student’s t probability density.


Syntax: @dtdist(x, v)
x: number
v: number
Return: number

Evaluates the probability density function,


v1
G  ------------ v  1
–--------------------
 2  2
x  2
 
f  x, v   ---------------------------- 1  -----
--1-   v 
v
 vp  G  ---
2
 2

for –   x   , and v  0

Examples
= @dtdist(0, 1)

returns 0.31830....

Cross-references
See also @ctdist (p. 775), @tdist (p. 1144), @qtdist (p. 1056), and @rtdist (p. 1099).

@dtoo Workfile Functions

Date-to-(workfile) observation.
Syntax: @dtoo(str)
str: string, alpha, svector
Return: integer, series, vector
848—Function Reference: D

Returns the observation number corresponding to the workfile date contained in the string.
The observation number is relative to the start of the current workfile range, not the current
sample.

Note that EViews will use the global default settings for the Month/Day order in dates to
determine the ordering of days and months in the string.

@dtoo will generate an error if used in a panel structured workfile.

Examples
Suppose that the workfile contains quarterly data from 1990q1 to 2020q4. Consider the com-
mands
scalar obsnum = @dtoo("1994m01")
scalar gdpval1 = gdp(obsnum + 10)
scalar gdpval2 = gdp(@dtoo("1994m01") + 10)

The first line returns 17, the observation in the workfile corresponding to 1990q1, and the
latter two find the value of GDP in 1996q3. Note that since we are assigning the value to a
scalar on the left, the argument in GDP is interpreted as an element, not a lag.

The command
series dser = @dtoo("12/1/1999")

fills DSER with the observation number corresponding to “12/1/1999” for each observation
in the workfile sample, where the months and days are interpreted using the global settings.

If the alpha series ASER contains dates,


series dser = @dtoo(aser)

fills DSER with the observation number corresponding to the string dates in ASER for each
observation in the workfile sample.

If AVEC is an svector, the command


vector dvec = @dtoo(avec)

fills DVEC with the observation numbers associated with the strings in AVEC.

Cross-references
See also @otod (p. 1019).
@duplic—849

@dunif Element Functions

Uniform probability density.


Syntax: @dunif(x, a, b)
x: number
a: number
b: number, b  a
Return: number

Evaluates the probability density function,


1
f  x, a, b   ------------ axb
b–a
and 0 otherwise.

Examples
= @dunif(4, 1, 6)

returns 0.2.

Cross-references
See also @cunif (p. 806), @qunif (p. 1059), and @runif (p. 1100).

@duplic Matrix Algebra

Duplication matrix.
Syntax: @duplic(n)
n: integer
Return: matrix

The duplication matrix transforms the half vectorization of a sym matrix to the full vector-
ization of the matrix.
2
Given the n  n sym matrix S , returns the n  n  n  1   2 matrix D , which satisfies
vec(S)  D  vech(S)
Examples
sym s1 = @unvech(@mnrnd(15))
vector diff = @vec(s1) - @duplic(s1.@cols) * @vech(s1)

demonstrates the properties of the duplication matrix since DIFF equals zero.
850—Function Reference: D

Cross-references
See also @commute (p. 763), @duplicinv (p. 850), and @elimin (p. 867)

@duplicinv Matrix Algebra

Inverse duplication matrix.


Syntax: @duplicinv(n)
n: integer
Return: matrix

The inverse of the duplication matrix transforms the vectorization of a sym matrix to the
half vectorization of the matrix.
+ 2
Returns D , the n  n  1   2  n Moore-Penrose inverse of the duplication matrix where
+ –1
D   DD  D
for D , the duplication matrix satisfying
vec(S)  D  vech(S)

for an n  n symmetric matrix S , so that


+
D  vec(S)  vech(S)
Examples
The commands
sym s2 = @unvech(@mnrnd(15))
vector diff = @duplicinv(s2.@cols) * @vec(s2) - @vech(s2)

demonstrates the properties of the inverse duplication matrix since DIFF equals zero.

Cross-references
See also @commute (p. 763), @duplic (p. 849), and @elimin (p. 867)
@dupselem—851

@dupselem Series Utility | Matrix Transformation

Duplicate identifier within group.

Identifier for the observation within the duplicate group, enumerating observations with the
same values.
Syntax: @dupselem(x1,[x2, x3, ... ], [s])
x: series, alpha, group, vector, matrix
x#: series, alpha, group, vector, matrix
s: (optional) sample string or object when the x are series, alpha, and
groups and assigning to series
Return: series, vector

For series, alpha, and groups, a duplicate is defined as two observations having identical
values for all of variables given by the arguments.

For vectors and matrix objects, a duplicate is defined as two row identifiers having identical
values in each of the vector and matrix objects given by the arguments.

Once sets of duplicates are identified, the observations or rows within each set are enumer-
ated. For a set consisting of n duplicated values, the enumerated values are simply the inte-
ger values from 1 to n.

Examples
Let X be a series of length 10 that alternates between 0 and 1. Then
show @dupselem(x)

will display a series whose observations are 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, which enumerates the


observations that share a common X value.

Let MAT be a matrix whose rows correspond to different observations. Then


vector delems = @dupselem(mat)

is a (column) vector of within-group observation IDs.


852—Function Reference: D

Cross-references
See @dupsid (p. 852) and @dupsobs (p. 853).

See also @uniquevals (p. 1169).

@dupsid Series Utility | Matrix Transformation

Duplicate group identifier.

Identifier for the duplicate group assigned to the observation.


Syntax: @dupsid(x1,[x2, x3, ... ], [s])
x: series, alpha, group, vector, matrix
x#: series, alpha, group, vector, matrix
s: (optional) sample string or object when the x are series, alpha, and
groups and assigning to series
Return: series, vector

For series, alpha, and groups, a duplicate is defined as two observations having identical
values for all of variables given by the arguments.

For vectors and matrix objects, a duplicate is defined as two row identifiers having identical
values in each of the vector and matrix objects given by the arguments.

Once sets of duplicates are identified, the observations or rows within each set are all
assigned a group identifier ranging from 1 to n, where n is the number of groups with com-
mon values.

Examples
Let X be a series of length 10 that alternates between 0 and 1. Then
show @dupsid(x)

will display a series whose observations alternate between the group numbers 1 and 2
(observations whose value in X is 0 belong to group 1, observations whose value in X is 1
belong to group 2).

Let MAT be a matrix whose rows correspond to different observations. Then


vector dids = @dupsid(mat)

returns a (column) vector of group IDs.


@dupsobs—853

Cross-references
See @dupselem (p. 851) and @dupsobs (p. 853).

See also @uniquevals (p. 1169).

@dupsobs Series Utility | Matrix Transformation

Duplicate group counts.

Count of the number of occurrences that are in each observation’s or row’s duplicate group.
Syntax: @dupsobs(x1,[x2, x3, ... ], [s])
x: series, alpha, group, vector, matrix
x#: series, alpha, group, vector, matrix
s: (optional) sample string or object when the x are series, alpha, and
groups and assigning to series
Return: series, vector

For series, alpha, and groups, a duplicate is defined as two observations having identical
values for all of variables given by the arguments.

For vectors and matrix objects, a duplicate is defined as two row identifiers having identical
values in each of the vector and matrix objects given by the arguments.

Once the sets of duplicates are identified, the observations or rows are within each set are
counted, and the function produces n, the number of observations in the group to which
each observation belongs.

An observation containing a unique combination of values among series, alphas, or groups


s1, s2, etc., will therefore have the value one, while any duplicated observation will have a
value larger than one.

Examples
Let x be a series of length 10 that alternates between 0 and 1. Then
show @dupsobs(x)

will return a linked series whose observations are all 5s since the size of both groups is 5.

Let MAT be a matrix whose rows correspond to different observations. Then


vector dobs = @dupsobs(mat)

is a (column) vector of within-group observation IDs.


854—Function Reference: D

Cross-references
See @dupselem (p. 851) and @dupsid (p. 852).

See also @uniquevals (p. 1169).

@during Workfile Functions

Indicator for whether an observation is between two dates


Syntax: @during(d)
d: string, alpha
Return: series

Returns a series containing indicators for whether each observation post-dates the first date
d1 and precedes the end of the second date d2 of the range d.
• For dates in d that are of equal or lower frequency than the observation, the results
are (0, 1) indicators of whether the observation matches or is in the interval.
• For dates in d that are of higher frequency than the observation, the results (0, n)
reflect the fraction of the observation that is in the interval.

Note that the behavior of this function differs from @before (p. 721), in that it includes
observations between the beginning and end of the final period that are not included when
you apply @before to the final period.

Examples
Suppose that we have a quarterly workfile with data from 2020q1 to 2023q4 that we create
with the command:
workfile q 2020 2023

The command
series during_y = @during("2021 2022")

uses a lower-frequency “yearly” date to creates the series DURING_Y containing the value 1
from 2022q1 through the 2022q4, and 0 elsewhere.

Using a “quarterly” date,


series during_q = @during("2021q3 2022q2")

creates the series DURING_Q containing the value 1 from 2021q3 through 2022q2 and 0 else-
where.

The command using a higher frequency “monthly” date


series during_m = @during("2021m6 2022m5")
@dweib—855

generates the series DURING_M containing a fractional value for 2021q2, 1 from 2021q3
through 2022q1, a fractional value for 2022q2, and the 0 elsewhere.

For the fractional 2021q2 value, there are 60 days in 2021-Apr and 2021-May that precede the
starting “2021m6” date. There are 91 days in the full quarter, so the fractional included value
for 2021q2 is (91-60)/91 = 0.32967.

For the fractional 2022q2 value, there are 61 days in 2021-April and 2021-May that precede
the end of the “2022m5” date. There are 91 days in the full quarter, so the fractional before
value for 2022q2 is 61/91 = 0.6793.

Cross-references
See also @after (p. 716) and @before (p. 721).

@dweib Element Functions

Weibull probability density.


Syntax: @dweib(x, m, a)
x: number, x  0
m: number, m  0
a: number, a  0
Return: number

Evaluates the probability density function,


–a a – 1 a
f  x, m, a   am x exp  –  x  m  

for x  0 and 0 elsewhere.

Examples
= @dweib(@log(2), 1, 1)

returns 0.5.

Cross-references
See also @cweib (p. 808), @qweib (p. 1060), and @rweib (p. 1104).
856—Function Reference: D

@dwish Element Functions

Wishart probability density.


Syntax: @dwish(X, S, n)
@dwishc(X, S, n)
@dwishi(X, S, n)
@dwishic(X, S, n)
X: sym, p  p
S: sym, matrix, p  p
n: number, n  p – 1
Return: number

Evaluate the Wishart distribution W p  S, n  density function for sym values of X, and S .

The Wishart density is given by


n – p – 1-
---------------------
2
X
f  X S, n   --------------------------------------------------------
–1
-
np tr  S X 
------ --n- ------------------------
n
S G p  ---  e
2 2 2
2
2

where X and S are symmetric p  p matrices, and n  p – 1 .

There are four different forms of the density evaluation function, corresponding to different
ways of specifying S . The forms are distinguished by different suffixes that are applied to
the base “@dwish” command and how they change the interpretation of the S matrix argu-
ment:
@dwish “” Supply S .
@dwishc “c” Supply the Cholesky decomposition of S .
This form is more efficient when performing multiple
draws from the same distribution (compute the Chole-
sky once, but sample many times).
–1
@dwishi “i” Supply S .
This form is more efficient than explicitly inverting
–1
S to supply S .
–1
@dwishic “ic” Supply the Cholesky decomposition of S .
This form combines the efficiencies of the Cholesky
and inverse forms.
@dwish—857

X  W p  S, n  is generally thought of as the accumulated scatter matrix of n random draws


from N  0, S  , i.e., x i  N  0, S  ,
n
X   xi xi  ,
i1

though the mathematical definition has been extended to cover real-valued n.


–1
Note that if X is a Wishart random variable, then X follows an inverse Wishart distribu-
tion:
–1 –1
X  W p  S, n   X  Wp  S , n 

Examples
= @dwish(@identity(3), @identity(3), 5)

returns 0.00018....

Cross-references
See also @rwish (p. 1104), @diwish (p. 840), and @riwish (p. 1079).
858—Function Reference: D
Function Reference: E—859

Function Reference: E
@ebtw ..................Element by element test for whether values are between two other
values (p. 860).
@ediv ...................Element by element division of two matrices (p. 861).
@eeq ....................Element by element equality comparison of two data objects
(p. 861).
@eeqna ................Element by element equality comparison of two data objects with
NAs treated as ordinary value for comparison (p. 862).
@ege ....................Element by element tests for whether the elements in the data
objects are greater than or equal to corresponding elements in
another data object (p. 863).
@egt.....................Element by element tests for whether the elements in the data
object strictly greater than corresponding elements in another data
object (p. 863).
@eigenvalues........Vector of eigenvalues of a sym (p. 864).
@eigenvectors.......Matrix whose columns contain the eigenvectors of a matrix
(p. 864).
@einv...................Element by element inverses of a matrix (p. 865).
@eisna .................Element by element missing value tests of data objects (p. 865).
@ele .....................Element by element tests for whether the elements in the data
object are less than or equal to corresponding elements in another
data object (p. 866).
@elimin................Elimination matrix (p. 867).
@elt......................Element by element tests for whether the elements in the data
object are strictly less than corresponding elements in another data
object (p. 867).
@emax .................Element by element maximums of two conformable data objects
(p. 868).
@emin..................Element by element minimums of two conformable data objects
(p. 868).
@emult.................Element by element multiplication of two matrix objects (p. 869).
@enddate .............Last possible date of observation (p. 870).
@eneq ..................Element by element inequality comparison of two data objects
(p. 870).
@eneqna ..............Element by element inequality comparison of two data objects with
NAs treated as ordinary value for comparison (p. 871).
@enisna ...............Element by element non-missing value tests of data objects
(p. 872).
@env....................Windows environment variable string (p. 872).
860—Function Reference: E

@epow ................ Raises each element in a matrix to a power (p. 873).


@eqna ................. Test for equality of values, treating NAs and null strings as ordinary
and not missing values (p. 873).
@equaloption....... Equals-to option value provided in the exec or run commands
(p. 875).
@erecode ............. Element by element recode of matrices (p. 876).
@erf..................... Error function (Gauss error function) (p. 876).
@erfc ................... Complementary (Gauss) error function (p. 877).
@errorcount......... Number of errors encountered running a program (p. 878).
@event ................ Event identifier for observation (p. 878).
@evpath .............. Directory path of the EViews executable (p. 877).
@exp ................... Exponential function (p. 879).
exp....................... Exponential function (p. 879).
@explode ............. Square matrix from a sym matrix object (p. 880).
@expm1 .............. Exponential function minus (p. 880).

@ebtw Matrix Element Functions

Element by element test for whether values are between two other values.
Syntax: @ebtw(x, v1, v2)
x: numeric or alphanumeric object
v1: numeric or alphanumeric object
v2: numeric or alphanumeric object
Return: vector or matrix object
where v1 and v2 correspond to the low and high values of the range.

Returns indicators equal to 1 for elements where x is greater than or equal to v1 and less than or
equal to v2, and 0 otherwise.

Examples
vector d1 = @ebtw(x, 10, 100)

creates a dummy variable that takes the value 1 where the value of X is in the range defined
by the values 10 and 100.
vector d2 = @ebtw(x, lowvals, highvals)

creates a dummy variable that takes the value 1 where the value of X is in the range defined
by the series LOWVALS and HIGHVALS.
vector d3 = @ebtw("myval", svalslow, svalshigh)
@eeq—861

tests for whether the string “myval” is between the low and high values in the string vectors
SVALSLOW and SVALSHIGH.

Cross-references
See also @between (p. 725) and @inlist (p. 921).

@ediv Matrix Element Functions

Element by element division of two numeric objects.


Syntax: @ediv(m1, m2)
m1: numeric object
m2: numeric object
Return: vector or matrix object

Returns the element by element division of two numeric objects.

Each element of the returned matrix is equal to the corresponding element in m1 divided by
the corresponding element in m2.

Note m1 and m2 must be of identical dimensions.

Examples
Let X and Y be matrices of IID normal variates. Then
matrix Z = @ediv(X, Y)

creates Z, a matrix of IID Cauchy variates.

Cross-references
See also @einv (p. 865), @emult (p. 869), and @epow (p. 873).

@eeq Matrix Element Functions

Element by element equality comparison of two data objects.


Syntax: @eeq(m1, m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns the element by element test of equality between numeric or alphanumeric objects.

Each element of the returned object is equal to 1 or 0 depending on whether the correspond-
ing element in m1 is equal to the corresponding element in m2.
862—Function Reference: E

Note m1 and m2 must be of identical dimensions.

Examples
Let X and Y be m  n matrices. Then
= @eeq(X, Y)

returns an m  n binary matrix that indicates where X and Y match (on 0 or on 1).

Cross-references
See also @ege (p. 863), @egt (p. 863), @ele (p. 866), and @elt (p. 867).

See also @eeqna (p. 862), @eneq (p. 870), and @eneqna (p. 871).

@eeqna Matrix Element Functions

Element by element equality comparison of two data objects with NA handling.


Syntax: @eeqna(m1, m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns the element by element test of equality between numeric or alphanumeric objects.
NAs and missing strings are treated as ordinary values for purposes of comparison.

Each element of the returned matrix is equal to 1 or 0 depending on whether the corre-
sponding element in m1 is equal to the corresponding element in m2.

Note m1 and m2 must be of identical dimensions.

Examples
Let X and Y be m  n matrices. Then
= @eeqna(X, Y)

returns an m  n binary matrix that indicates where X and Y match (on 0, 1, or NA).

Cross-references
See also @eisna (p. 865), @ege (p. 863), @egt (p. 863), @ele (p. 866), and @elt (p. 867).

See also @eeq (p. 861), @eneq (p. 870), and @eneqna (p. 871).
@egt—863

@ege Matrix Element Functions

Element by element greater than or equal tests of two data objects.


Syntax: @ege(m1, m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns a test for whether the elements in the data object m1 are greater than or equal to the
corresponding elements in m2.

Each element of the returned matrix is equal to 1 or 0 depending on the outcome of the com-
parison.

Note m1 and m2 must be of identical dimensions.

Examples
Let X and Y be m  n matrices. Then
= @ege(X, Y)

returns an m  n binary matrix indicating places where X is greater than or equal to Y.

Cross-references
See also @eisna (p. 865), @egt (p. 863), @ele (p. 866), and @elt (p. 867).

See also @eeq (p. 861), @eeqna (p. 862), @eneq (p. 870), and @eneqna (p. 871).

@egt Matrix Element Functions

Element by element greater than tests of two data objects


Syntax: @egt(m1,m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns a test for whether the elements in the object m1 are greater than the corresponding
elements in m2.

Each element of the returned matrix is equal to 1 or 0 depending on the outcome of the com-
parison.
864—Function Reference: E

Note m1 and m2 must be of identical dimensions.

Examples
Let X and Y be m  n matrices. Then
= @egt(X, Y)

returns an m  n binary matrix indicating places where X is greater Y.

Cross-references
See also @eisna (p. 865), @ege (p. 863), @ele (p. 866), and @elt (p. 867).

See also @eeq (p. 861), @eeqna (p. 862), @eneq (p. 870), and @eneqna (p. 871).

@eigenvalues Matrix Algebra

Eigenvalues of symmetric matrix.


Syntax: @eigenvalues(s)
s: sym
Return: vector

Returns a vector containing the eigenvalues of the sym s.

The eigenvalues are those scalars l that satisfy Sx=lx where S is the sym associated
with the argument s . The eigenvalues are arranged in ascending order.

Examples
sym s1 = @unvech(@mnrnd(15))
vector v1 = @eigenvalues(s1)

creates V1, a vector of eigenvalues of S1.

Cross-references
See also @eigenvectors (p. 864), @det (p. 835), and @trace (p. 1147).

@eigenvectors Matrix Algebra

Eigenvectors of symmetric matrix.


Syntax: @eigenvectors(s)
s: sym
Return: matrix

Returns a square matrix whose columns are the eigenvectors of the sym s.
@eisna—865

Each eigenvector v satisfies Sv  nv , where S is the symmetric matrix given by s, and


where n is the eigenvalue associated with the eigenvector v. The eigenvalues are arranged in
ascending order, and the columns of the eigenvector matrix correspond to the sorted eigen-
values.

Examples
sym s1 = @unvech(@mnrnd(15))
matrix m1 = @eigenvectors(s1)

creates M1, a matrix of eigenvectors of S1.

Cross-references
See @eigenvalues (p. 864).

@einv Matrix Element Functions

Element by element inverses (reciprocals) of a numeric data object.


Syntax: @einv(m)
m: numeric data object
Return: numeric data object

Returns the element by element inverse of a data object.

Each element of the returned object is equal to 1 divided by the corresponding element of
the input object.

Examples
Let C1 be a matrix of IID Cauchy variates with scale s . Then
= @einv(c1)
–1
returns a matrix of IID Cauchy variates with scale s .

Cross-references
See also @ediv (p. 861), @emult (p. 869), and @epow (p. 873).

@eisna Matrix Element Functions

Element by element missing value tests of data objects.


Syntax: @eisna(m)
m: numeric or alphanumeric object
Return: vector or matrix object
866—Function Reference: E

Returns a test for whether the elements in the data object m are numeric missing values, or
empty strings.

Each element of the returned matrix is equal to 1 or 0 depending on the outcome of the com-
parison. Missing values are set to 1, and non-missing are set to 0.

Examples
Let X be an m  n matrix. Then
= @eisna(X)

returns an m  n binary matrix indicating places where X is missing.

Cross-references
See also @enisna (p. 872), @ege (p. 863), @egt (p. 863), and @elt (p. 867).

See also @eeq (p. 861), @eeqna (p. 862), @eneq (p. 870), and @eneqna (p. 871).

@ele Matrix Element Functions

Element by element less than or equal to tests of data objects.


Syntax: @ege(m1, m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns a test for whether the elements in the data object m1 are greater than or equal to the
corresponding elements in m2.

Each element of the returned matrix is equal to 1 or 0 depending on the outcome of the com-
parison.

Note m1 and m2 must be of identical dimensions.

Examples
Let X and Y be m  n matrices. Then
= @ele(X, Y)

returns an m  n binary matrix indicating places where X is less than or equal to Y.

Cross-references
See also @eisna (p. 865), @ege (p. 863), @egt (p. 863), and @elt (p. 867).

See also @eeq (p. 861), @eeqna (p. 862), @eneq (p. 870), and @eneqna (p. 871).
@elt—867

@elimin Matrix Algebra

Elimination matrix.
Syntax: @elimin(n)
n: integer
Return: matrix

The elimination matrix transforms the half vectorization of a sym matrix to the vectorization
of the matrix.
2
Returns the n  n  1   2  n matrix L , which satisfies
vech(S)  L  vec(S)

for an n  n sym matrix S ,

Examples
sym s1 = @unvech(@mnrnd(15))
vector diff = @vech(s1) - @elimin(s1.@cols) * @vec(s1)

demonstrates the properties of the duplication matrix since DIFF equals zero.

Cross-references
See also @commute (p. 763), @duplic (p. 849), and @duplicinv (p. 850).

@elt Matrix Element Functions

Element by element less than tests of data objects matrices.


Syntax: @elt(m1, m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns a test for whether the elements in the data objector m1 are less than the correspond-
ing elements in m2.

Each element of the returned matrix is equal to 1 or 0 depending on the outcome of the com-
parison.

Note m1 and m2 must be of identical dimensions.


868—Function Reference: E

Examples
Let X and Y be m  n matrices. Then
= @elt(X, Y)

returns an m  n binary matrix indicating places where X is less than Y.

Cross-references
See also @eisna (p. 865), @ege (p. 863), @egt (p. 863), and @ele (p. 866).

See also @eeq (p. 861), @eeqna (p. 862), @eneq (p. 870), and @eneqna (p. 871).

@emax Matrix Element Functions

Element by element maximums of two data objects.


Syntax: @emax(m1, m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns the element maximum of the conformable data objects m1 and m2.

Examples
Suppose there are n individuals deciding between two courses of action. Let U1 be an n-vec-
tor whose i-th element represents the utility the i-th individual derives from taking the first
action. Define U2 similarly. Then
= @emax(u1, u2)

returns an n-vector of utilities that results from each individual taking the course of action
that maximizes utility.

Cross-references
See also @emin (p. 868).

@emin Matrix Element Functions

Element by element minimums of two data objects matrices.


Syntax: @emin(m1, m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object
@emult—869

Returns the element minimum of the conformable matrices m1 and m2.

Examples
Suppose there are n individuals deciding between two courses of action. Let L1 be an n-vec-
tor whose i-th element represents the loss the i-th individual experiences from taking the
first action. Define L2 similarly. Then
= @emin(l1, l2)

returns an n-vector of losses that results from each individual taking the course of action
that minimizes loss.

Cross-references
See also @emax (p. 868).

@emult Matrix Element Functions

Element by element multiplication of two numeric data objects.


Syntax: @emult(m1, m2)
m1: numeric object
m2: numeric object
Return: numeric object

Returns the element by element multiplication of two numeric objects.

Each element of the returned object is equal to the corresponding element in m1 multiplied
by the corresponding element in m2.

Note m1 and m2 must be of identical dimensions.

Examples
Let M1 and M2 be m  n matrices of IID log-normal variates. Then
matrix m3 = @emult(m1, m2)

creates M3, an m  n matrix of IID log-normal variates.

Cross-references
See also @einv (p. 865), @ediv (p. 861), and @epow (p. 873).
870—Function Reference: E

@enddate Workfile Functions

Last possible date of observation.


Syntax: @enddate
Return: series

Returns the date number associated with the end date of each observation in the workfile.

The end date number associated with an observation is the last (largest) date number corre-
sponding to the observation date interval.

Examples
series dt = @enddate

saves the enddate numbers into the series DT. The default display format for these numbers
will match the workfile frequency, but you may work with and display the series values as
numbers.
alpha dts_1 = @datestr(@enddate,"yyyy:q")
alpha dts_2 = @strdate("yyyy:q")

Create two string series with the end observation dates formatted in “yyyy:q” format.

Cross-references
See “Date Numbers,” on page 106 and “Date Formats” on page 106.

See also @date (p. 814), @datestr (p. 824) and @strdate (p. 1128).

@eneq Matrix Element Functions

Element by element inequality comparison of two data objects.


Syntax: @eneq(m1,m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns the element by element test of inequality between two data objects. Each element of
the returned matrix is equal to 1 or 0 depending on whether the corresponding element in
m1 is not equal to the corresponding element in m2. Note m1 and m2 must be of identical
dimensions.
@eneqna—871

Examples
Let X and Y be m  n binary matrices. Then
= @eneq(X, Y)

returns an m  n binary matrix that indicates where X and Y do not match (on 0 or on 1).

Cross-references
See also @eisna (p. 865), @ege (p. 863), @egt (p. 863), @ele (p. 866), and @elt (p. 867).

See also @eeq (p. 861), @eeqna (p. 862), and @eneqna (p. 871).

@eneqna Matrix Element Functions

Element by element inequality comparison of two data objects with NA handling.


Syntax: @eneqna(m1, m2)
m1: numeric or alphanumeric object
m2: numeric or alphanumeric object
Return: vector or matrix object

Returns the element by element test of inequality between two data objects. NAs and empty
strings are treated as ordinary values for purposes of comparison.

Each element of the returned matrix is equal to 1 or 0 depending on whether the corre-
sponding element in m1 is not equal to the corresponding element in m2.

Note m1 and m2 must be of identical dimensions.

Examples
Let X and Y be m  n matrices. Then
= @eneqna(X, Y)

returns an m  n binary matrix that indicates where X and Y do not match (on 0, 1, or NA).

Cross-references
See also @ege (p. 863), @egt (p. 863), @ele (p. 866), and @elt (p. 867).

See also @eeq (p. 861), @eeqna (p. 862), and @eneq (p. 870).
872—Function Reference: E

@enisna Matrix Element Functions

Element by element non-missing value tests of data objects.


Syntax: @enisna(m)
m: numeric or alphanumeric object
Return: vector or matrix object

Returns a test for whether the elements in the data object m are numeric non-missing val-
ues, or non-empty strings.

Each element of the returned matrix is equal to 1 or 0 depending on the outcome of the com-
parison. Non-missing values are set to 1, and missing are set to 0.

Examples
Let X be an m  n matrix. Then
= @enisna(X)

returns an m  n binary matrix indicating places where X is not missing.

Cross-references
See also @eisna (p. 865), @ege (p. 863), @egt (p. 863), and @elt (p. 867).

See also @eeq (p. 861), @eeqna (p. 862), @eneq (p. 870), and @eneqna (p. 871).

@env Support Functions

Windows environment variable string.


Syntax: @env(str)
str: string
Return: string

Returns the value of the Windows environment variable str.

Examples
@env("username")
returns the user-name of the current logged in user.
@env("computername")
returns the name of the computer.
@env("homepath")
@eqna—873

returns the path of the current logged in user.


The command
svector a = @env(@sfill("username", "computername", "homepath"))
returns the three strings in the svector object A.

@epow Matrix Element Functions

Element by element raise to a power in a data object.


Syntax: @epow(m1, m2)
m1: numeric object
m2: numeric object
Return: numeric object

Returns a matrix where every element is equal to the corresponding element in m1 raised to
the power given by m2.

Examples
Let X be a matrix of IID standard normal variates. Then
= @epow(x, 2)

returns a matrix of IID chi-square variates with unit degree of freedom.

Cross-references
See also @ediv (p. 861), @einv (p. 865), and @emult (p. 869).

@eqna Series Utility | Matrix Utility

Tests for equality of values.


Syntax: @eqna(arg1, arg2)
arg1: number or string
arg2: number or string
Return: number

Tests for equality of the arg1 and arg2, treating NAs and null strings as ordinary, and not as
missing values. Simple equality testing which propagates null string NAs may be performed
using the “=” binary comparison operator.

Return value is an integer (0, 1). Arguments which test as equal return a 1, and 0 otherwise.

When used with series objects, the test is performed for every observation in the workfile
sample. Note that when used with matrix objects, the comparison is an equality test of all of
874—Function Reference: E

the elements of the two matrices, and will return 0 if any element comparison is false. Indi-
vidual element tests are available in @eeqna (p. 862)

Examples
The test
scalar f = @eqna(NA, 2)

returns the value 0, not an NA.

Consider the comparison


vector v1 = @fill(1, 2, 2)
scalar f2 = @eqna(v1, 2)

compares the entire vector V1 to 2, and returns 0 since some of the elements of V1 are not
equal to 2. Note that the comparison is an equality test of the entire vector that returns a 0 if
any element is not equal, and a 1 if all elements are equal, ignoring NAs.

If SER1 and SER2 are numeric series,


series s2 = @eqna(ser1, ser2)

tests SER1 and SER2 for equality, ignoring NAs, for each observation in the workfile sample.

Define the string objects


string s1 = "abc"
string s2 = ""

Then
scalar b1 = @eqna("abc", "abc")
scalar b2 = @eqna("abc", s1)

sets the scalar objects B1 and B2 to 1, while


scalar c1 = @eqna("", "def")
scalar c2 = @eqna(s2, "def")
scalar c3 = @eqna(s1, s2)

sets C1, C2, and C3 to 0.

If ALPHA1 and ALPHA2 are alpha series,


series d1 = @eqna(alpha1, "abc")
series d2 = @eqna(alpha1, s1)
series d3 = @eqna(alpha1, alpha2)

perform the equality test using ALPHA1 and ALPHA2 for each observations in the workfile
sample.
@equaloption—875

If SVEC1 and SVEC2 are svectors,


scalar sc1 = @eqna(svec1, "abc")
scalar sc2 = @eqna(svec1, svec2)

perform the equality test of SVEC1 against “abc”, and the contents of SVEC2. Note that this
is a full equality test of SVEC1 against the string, or against each element of SVEC2, and that
the test will return a 0 if any element is not equal, and a 1 if all elements are equal (ignoring
empty strings).

Cross-references
See also @eeqna (p. 862), @eisna (p. 865), @isna (p. 927), and @neqna (p. 1010).

@equaloption Support Functions

Equals-to option value provided in the exec or run commands.


Syntax: @equaloption(str)
str: string
Return: string

returns the text to the right of the “str=” option provided in the exec (p. 444) or run
(p. 581) commands.

If the str keyword is not found, the function will return an empty string.

Example
For example, if you have specified the option “kernel=tri” in your exec command,
string opt = @equaloption("kernel")

will return the string “TRI”.

Cross-references
See exec (p. 444) and run (p. 581).
876—Function Reference: E

@erecode Matrix Element Functions

Element by element recode of data objects.


Syntax: @erecode(m1, m2, m3)
m1: numeric object
m2: numeric or alphanumeric object
m3: numeric or alphanumeric object
Return: numeric or alphanumeric object

Returns the element recode using the conformable numeric condition object m1 and the
matrices m2 and m3. If an element of m1 is non-zero, then assign the value using the corre-
sponding element of m2, otherwise use the corresponding value of m3.

Examples
Let M1 be a matrix. Then
= @erecode(@egt(M1, 0), M1, na)

returns a matrix that is identical to M1 except that negative values are replaced with NAs.

Cross-references
See also @eeq (p. 861).

@erf Element Functions

Error function (Gauss error function).


Syntax: @erf(x)
x: number
Return: number
x
2 2
erf  x   -------  exp  – t  dt
p0
for x  0 .

Examples
= @erf(1/@sqrt(2))

returns 0.68268... (area under the normal curve within 1 standard deviation of the mean).
@errorcount—877

Cross-references
See also @erfc (p. 877).

@erfc Element Functions

Complimentary (Gauss) error function.


Syntax: @erfc(x)
x: number
Return: number

2 2
erfc  x   -------  exp  – t  dt  1 – erf  x  .
px

for x  0 .

Examples
= @erfc(1/@sqrt(2))

returns 0.31731... (area under the normal curve beyond 1 standard deviation of the mean).

Cross-references
See also @erf (p. 876).

@errorcount Support Functions

Number of errors encountered running a program.


Syntax: @errorcount
Return: integer

Returns a scalar containing the number of errors encountered during program execution.

Cross-references
See also @maxerrcount (p. 966), setmaxerrs (p. 588), clearerrs (p. 393), seterr
(p. 587), and seterrcount (p. 587).
878—Function Reference: E

@event Workfile Functions

Event identifiers for observation.


Syntax: @event(h[, b])
h: string
b: (optional) string
Return: series

where h is the one-off event specification and b is a basis specification.

Returns the proportion or identifier of a one-off event covered by the observation, for each
observation in the workfile. If the workfile has a regular frequency and spans the entire
event, the returned series will sum to one over all observations. If the workfile is irregular or
does not span the entire event, the series may sum to less than one due to the observations
that have been omitted.

The optional basis parameter may be used to specify that only certain days of the week or
times of the day should be included as part of the holiday. This parameter has the format
"start_weekday-end_weekday[, start_time-end_time]"

e.g. “mon-thu” or “mon-sun,10am-4pm”.

@event is similar to @holiday (p. 901), but handles only a single non-repeating date or
date range and only the basis option.

Examples
"1980Q3"

Cross-references
See “Event Function,” on page 312 for extensive discussion. See also @holiday (p. 901).

@evpath Support Functions

Directory path of the EViews executable


Syntax: @evpath
Return: string

Returns a string containing the directory path for the EViews executable.

Examples
If your currently executing copy of EViews is installed in “d:\eviews”, then
exp—879

%y = @evpath

assigns a string of the form “D:\EVIEWS”.

Cross-references
See also cd (p. 388), @datapath (p. 813), @addinspath (p. 714), and @temppath
(p. 1145).

@exp Element Functions

Exponential function.
Syntax: @exp(x)
x: number
Return: number
x
Returns y  exp  x   e .

Examples
= @exp(1)

returns 2.71828....

Cross-references
See also exp (p. 879) and @expm1 (p. 880).

exp Element Functions

Exponential function.
Syntax: exp(x)
x: number
Return: number
x
Returns y  exp  x   e .

Examples
= exp(1)

returns 2.71828....

Cross-references
See also @exp (p. 879) and @expm1 (p. 880).
880—Function Reference: E

@explode Matrix Utility

Square matrix from a sym matrix.


Syntax: @explode(s)
s: sym
Return: matrix

Creates a square matrix from a sym s, by duplicating the lower triangle elements into the
upper triangle.

Examples
Let S be a sym object. Then
matrix m = @explode(s)

creates M, a matrix object whose size and elements are identical to those of S.

Cross-references
See also @implode (p. 919) and @implodeu (p. 920).

@expm1 Element Functions

Exponential function minus 1.


Syntax: @expm1(x)
x: number
Return: number
x
Returns y  e – 1 .

Provides higher precision calculation than direct evaluation using


@exp(x) - 1

for x near 0.

Examples
= @expm1(0.05)

returns 0.05127....

Cross-references
See also @exp (p. 879).
@fact—881

Function Reference: F
@fact....................Factorial function (p. 881).
@factlog ...............Natural logarithm of the factorial function (p. 882).
@fdist...................Upper tail of F-distribution (p. 882).
@fileexist..............Check for existence of a file on disk (p. 883).
@fill .....................Vector initialized from a list of values (p. 884).
@filledmatrix ........Matrix initialized with scalar value (p. 884).
@filledrowvector...Rowvector initialized with scalar value (p. 885).
@filledsym ...........Sym initialized with scalar value (p. 885).
@filledvector ........Vector initialized with scalar value (p. 886).
@first ...................The first non-missing value in the vector or series (p. 886).
@firstsby ..............First non-missing value in a series for each specified group (p. 887).
@floor ..................Largest number less than or equal to with optional precision
(p. 887).
@folderexist..........Check for existence of a folder on disk (p. 888).
@fracdiff...............Fractional difference of series data (p. 889).
@fv ......................Future value of annuity payments and (optional) initial lump sum
receipt (p. 889).

@fact Element Functions

Factorial function.
Syntax: @fact(x)
x: integer
Return: number

x  x – 1    1 x0
x!  
 1 x  0

for integer x  0 . Note that this function is subject to overflow for large x .
• @gamma may be used to obtain results for real valued x  0 .
• Related, stable calculations for the logarithm of @fact may be obtained using
@factlog.

Examples
= @fact(3)

returns 6.
882—Function Reference: F

Cross-references
See also @factlog (p. 882).

@factlog Element Functions

Natural logarithm of the factorial function.


Syntax: @factlog(x)
x: number
Return: number

for x  0 . Returns

 log  x!  x0
y   e
 0 x  0

• @gammalog may be used to obtain results for real valued x  0 .

Examples
= @factlog(3)

returns 1.79175... (the natural log of 6).

Cross-references
See also @fact (p. 881).

@fdist Element Functions

Upper tail of F-distribution.


Syntax: @fdist(x, v 1 , v 2 )
x: number
v1 : number, v 1  0
v2 : number, v 2  0
Return: number

Computes the upper tail of the cumulative distribution integral

 1
 x0
G  x v 1, v 2    
 x f  s v 1, v 2  ds x0

where
@fileexist—883

v 2 v 2
v 11 v 22 v – 2  2 – v  v   2
f  x v 1, v 2   -------------------------------------
-x 1  v2  v1 x  1 2
B  v 1  2, v 2  2 

for x  0 and 0 otherwise, and B is the beta function


1
a–1 b–1 G  a G  b 
B  a, b   t 1 – t dt  ------------------------
Ga  b
0

Note that the functions allow for fractional degrees of freedom parameters v 1 and v 2 .

Examples
= @fdist(1, 2, 2)

returns 0.5.

Cross-references
See also @cfdist (p. 739), @dfdist (p. 838), @qfdist (p. 1048), and @rfdist (p. 1073).

@fileexist Support Functions

Check for existence of a file on disk.


Syntax: @fileexist(str)
str: string
Return: integer

Check for an file’s existence. str should contain the full path and file name of the file you
want to check for. Returns a “1” if the file exists, and a “0” if it does not exist.

Examples
!exists = @fileexist("myfile.prg")

checks for the existence of MYFILE.PRG in the EViews working directory.


!exists = @fileexist("c:\users\william tell\myfile.prg")

checks for the existence of MYFILE.PRG in the specified directory.

Cross-references
See also @wdir (p. 1190) and @folderexist (p. 888)
884—Function Reference: F

@fill Matrix Utility

Vector initialized from a list of values.


Syntax: @fill(n1[, n2, n3, ...])
n#: number
Return: vector

Returns a vector containing the elements specified by the arguments to the function. The
vector will have length equal to the number of arguments. The maximum number of argu-
ments is 96.

Examples
vector v = @fill(1, 4, 6, 21.3)

Will return a 4 element vector, where the first element is set to 1, the second to 4, the third
to 6 and the fourth to 21.3.
vector pvals = @cnorm(@fill(-1.65, -1, .5, 1.76))

evaluates the cumulative normal distribution function for the vector of values {-1.65, -1.0,
0.5, 1.76}.

Cross-references
See @filledmatrix (p. 884), @filledrowvector (p. 885), @filledsym (p. 885), and
@filledvector (p. 886).

See also @sfill (p. 1111).

@filledmatrix Matrix Utility

Matrix initialized with scalar value.


Syntax: @filledmatrix(n1, n2, n3)
n1: integer
n2: integer
n3: number
Return: matrix

Returns a matrix with n1 rows and n2 columns, where each element contains the value n3.

Examples
= @filledmatrix(4, 3, @pi)
@filledsym—885

returns a 4  3 matrix whose elements all equal to p .

Cross-references
See @fill (p. 884), @filledrowvector (p. 885), @filledsym (p. 885), and @filled-
vector (p. 886).

@filledrowvector Matrix Utility

Rowvector initialized with scalar value.


Syntax: @filledrowvector(n1, n2)
n1: integer
n2: integer
Return: rowvector

Returns a rowvector of length n1, where each element contains the value n2.

Examples
= @filledrowvector(3, @pi)

returns a 3-element rowvector whose elements all equal to p .

Cross-references
See @fill (p. 884), @filledmatrix (p. 884), @filledsym (p. 885), and @filledvector
(p. 886).

@filledsym Matrix Utility

Sym initialized with scalar value.


Syntax: @filledsym(n1, n2)
n1: integer
n2: number
Return: sym

Returns an n1  n1 sym, where each element contains n2.

Examples
= @filledsym(3, @pi)

returns a 3  3 sym object whose elements all equal to p .


886—Function Reference: F

Cross-references
See @fill (p. 884), @filledmatrix (p. 884), @filledrowvector (p. 885), and
@filledvector (p. 886).

@filledvector Matrix Utility

Vector initialized with scalar value.


Syntax: @filledvector(n1, n2)
n1: integer
n2: number
Return: vector

Returns a vector of length n1, where each element contains the value n2.

Examples
= @filledvector(3, @pi)

returns a 3-element (column) vector whose elements all equal to p .

Cross-references
See @fill (p. 884), @filledmatrix (p. 884), @filledrowvector (p. 885), and
@filledsym (p. 885).

@first Basic Statistics

The first non-missing value in the data object.


Syntax: @first(m)
m: numeric or alphanumeric object
Return: number or string

Returns scalar containing the first non-missing values of the single column data object. The
series and alpha versions use the current workfile sample.

Examples
Let V be a vector of length 4 whose elements are NA, NA, 4.2, and 1.7. Then
= @first(v)

returns 4.2.
@floor—887

Cross-references
See also @cfirst (p. 740), @clast (p. 748), @cifirst (p. 744), and @cilast (p. 745).

See also @last (p. 940), @ifirst (p. 914), and @ilast (p. 915).

@firstsby By-Group Statistics

First non-missing value in a series or alpha for each group defined by distinct values.
Syntax: @firstsby(x, y[y1, y2, ... yn, s])
x: series, alpha
y1...yn series, alpha, group
s: (optional) sample string or object
Return: number, string

First non-missing value in each distinct value group computed using the current workfile or
specified sample.

Examples
show @firstsby(x, g1, g2)

produces a linked series of the by-group first non-missing values of the series x, where
members of the same group have identical values for both g1 and g2.

Cross-references
See also @lastsby (p. 941).

@floor Element Functions

Largest integer less than or equal to (with optional precision).


Syntax: @floor(x[, n])
x: number
n: (optional) integer
Return: number
• @floor(x) returns x , the largest integer that is less than or equal to x.
n n
• @floor(x, n) returns x  10  10 , the largest decimal number that is less than or
equal to x at the given precision.

The decimal offset n may be interpreted as the precision to use when computing the floor. If
n is not an integer, the integer floor n will be used.
888—Function Reference: F

Examples
= @floor(@pi)

returns 3.
= @floor(@pi,2)

returns 3.14.
= @floor(-@pi)

returns -4.

Cross-references
See also @ceil (p. 737).

@folderexist Support Functions

Check for existence of a folder on disk.


Syntax: @folderexist(str)
str: string
Return: integer

str should contain the full path of the folder you want to verify. Returns a “1” if the folder
exists, and a “0” if it does not exist.

Examples
!exists = @folderexist("backup")

checks for the existence of the folder BACKUP in the EViews working directory.
!exists = @folderexist("c:\users\william tell\backup")

checks for the existence of BACKUP in the specified directory.

Cross-references
See also @wdir (p. 1190) and @fileexist (p. 883).
@fv—889

@fracdiff Series Utility

Fractional difference of series data.


Syntax: @fracdiff(x, y[, s])
x: series
y: series
s: (optional) sample string or object
Return: series
n
Returns D  x  for series x for n  0 :

n i Gn  1
D x    – 1  --------------------------------------
i!  G  n  1 – i  k – i
-x (18.6)
i0

This function is panel aware.

Examples
show @fracdiff(@demean(x),1.5)
1.5
applies D  x  to the demeaned version of the series x.
Cross-references
See also d (p. 812).

@fv Element Functions

Future value of annuity payments and (optional) initial lump sum receipt.
Syntax: @fv(r, n, x[, v, bf])
r: number
n: integer
x: number
v: (optional) number
bf: (optional) number
Return: number

Compute future (negative) value of payment of an n-period annuity, with payments x and
rate r, and optional receipt of (positive) initial lump sum v.

If n is not an integer, the integer floor n will be used.


890—Function Reference: F

A non-zero value for the optional bf indicates that the payments are made at the beginning
of periods (annuity due) instead of ends (ordinary annuity).
• The future value of an initial lump sum followed by n-periods of ordinary annuity
payments:
n
n 1  r – 1
FVO  v   1  r  – x  ----------------------------------
r
• The future value of an initial lump sum followed by annuity due payments is:

n    1  r n – 1  n 
FVD  v   1  r  – x   ----------------------------------    1  r  – 1  
 r 
Examples
= @fv(0.05, 10, 100, 1000)

returns the value 371.1054, meaning that the issuer of the annuity stands to profit $371.11
once payments are done.

Cross-references
See also @nper (p. 1013), @pmt (p. 1040), @pv (p. 1044), and @rate (p. 1066).
@gamma—891

Function Reference: G
@gamma ..............(Complete) gamma function (p. 891).
@gammader .........First derivative of the gamma function (p. 892).
@gammainc..........Incomplete gamma function (p. 892).
@gammaincder.....Derivative of the Incomplete gamma integral (p. 893).
@gammaincinv .....Inverse of the incomplete gamma function (p. 894).
@gammalog..........Natural logarithm of the gamma function (p. 894).
@getmaindiagonal Extract main diagonal from matrix (p. 895).
@getnextname ......String containing next available name in the workfile (p. 895).
@getthistype .........Object type of active object (_this) (p. 896).
@gmean ...............Geometric mean (p. 896).
@grid ...................Vector containing equally spaced grid of values (p. 897).

@gamma Element Functions

(Complete) gamma function.


Syntax: @gamma(x)
x: number
Return: number

–t x – 1
Gx  e t dt
0

for x  0 .

Related, stable calculations for the logarithm of @gamma may be obtained using @gamma-
log (p. 894).

Examples
= @gamma(5)

returns 24 (equivalent to  5 – 1 ! ).
= @gamma(0.5)

returns 1.77245... (equivalent to p ).


Cross-references
See also @gammalog (p. 894), @gammader (p. 892), and @gammainc (p. 892).
892—Function Reference: G

@gammader Element Functions

Derivative (first) of the gamma function.


Syntax: @gammader(x)
x: number
Return: number
dG  x 
G  x   ---------------
dx
for x  0 .
Note: Euler’s constant, g  0.5772 , may be evaluated as g  – @gammader(1) .

Examples
= @gammader(1)

returns -0.57721....

Cross-references
See also @gamma (p. 891) and @digamma (p. 839).

@gammainc Element Functions

Incomplete gamma function.


Syntax: @gammainc(x, a[, u])
x: number
a: number
u: (optional) number
Return: number
x
1 –t a – 1
G  x a   ------------  e t dt
Ga
0

for x  0 and a  0 .

If the optional argument u is non-zero, return the upper-tail value:


1 – Gx a (18.7)

Examples
= @gammainc(1,1)
@gammaincder—893

returns 0.63212... (equivalent to 1 – exp  – 1  ).

Cross-references
See also @gamma (p. 891), @gammaincder (p. 893), and @gammaincinv (p. 894).

@gammaincder Element Functions

Derivative of the incomplete gamma integral.


Syntax: @gammaincder(x, a, c)
x: number
a: number
c integer
Return: number

Given the incomplete gamma integral for elements of x and a:


x
1 –t a – 1
G  x a   ------------  e t dt
Ga
0

for x  0 and a  0 , compute the derivative given by c where c is an integer from 1 to 5


indicating the desired derivative,

G G
-------- -------- -
1 2 - x a
 2 2 2
3 4 5 G  G  G
---------
- ------------- ----------
2 2
x xa a

If c is not an integer, the integer floor c will be used.

Examples
= @gammaincder(1,3,1)

returns 0.18393....

Cross-references
See also @gammainc (p. 892) and @gammaincinv (p. 894).
894—Function Reference: G

@gammaincinv Element Functions

Inverse of the incomplete gamma function.


Syntax: @gammainciv(p, a)
x: number
p: number
a: number
Return: number

Find the value of x satisfying:


x
1 –t a – 1
p  G  x a   ------------  e t dt
Ga
0

for 0  p  1 and a  0 .

Examples
= @gammaincinv(0,2)

returns 0.

Cross-references
See also @gammainc (p. 892) and @gammaincder (p. 893).

@gammalog Element Functions

Natural logarithm of the gamma function.


Syntax: @gammalog(x)
x: number
Return: number

–t x – 1
log G  x   log  e t dt
0

for x  0 .

Examples
= @gammalog(3)

returns 0.69314....
@getnextname—895

Cross-references
See also @digamma (p. 839) and @trigamma (p. 1152).

@getmaindiagonal Matrix Utility

Extract main diagonal from matrix.


Syntax: @getmaindiagonal(m)
m: matrix, vector, sym
Return: vector

Returns a vector created from the main diagonal of the matrix or sym object. The main diag-
onal is defined as the elements {(1, 1), (2, 2), ..., (k, k)} of the matrix, where k is the
smaller of the number of rows and columns.

Examples
If M1 is an n  n identity matrix, then
= @getmaindiagonal(m1)

returns an n-vector of ones.

Cross-references
See also @makediagonal (p. 961).

@getnextname Support Functions

Syntax: @getnextname(str)
str: string,
Return: string

Returns a string containing the next available variable name in the workfile, starting with str
(i.e. entering “result” will return “RESULT01” unless there is already a RESULT01, in which
case it will return “RESULT02”).

Examples
%objname = @getnextname("eqtest")
equation {%objname}.ls y c x1 x2 x3

assigns the next available name to the string variable %OBJNAME, and then uses the name
to estimate an equation in the workfile.
896—Function Reference: G

Cross-references
See also @isobject (p. 929).

@getthistype Support Functions

Object type of active object (_this)


Syntax: @getthistype
Return: string

If no workfile is open, or if no object has yet been opened in a workfile, the function will
return the string "NONE".

This latter behavior is in contrast to using the data member syntax “_this.@type”, which
will generate an error in cases like this where the active object is undefined.

Cross-references
See also the @type data member of each object in Chapter 1. “Object View and Procedure
Reference,” beginning on page 3.

See “The Active Object Keyword” on page 230 in the Command and Programming Reference
for a discussion of the _THIS active object.

@gmean Basic Statistics

Geometric mean.

Computes the geometric mean of the elements of x for x  0


Syntax: @gmean(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

The geometric mean is calculated as


1 T 
y  exp  ----  log  x t 
Tt  1 

For series calculations, EViews will use the current or specified workfile sample.
@grid—897

Examples
If x is a series of length 3 with elements 1, 2, and 4, then
= @gmean(x)

returns 2 (= the cube root of 8).

Cross-references
See also @mean (p. 971), @hmean (p. 900), and @trmean (p. 1154).

@grid Matrix Utility

Vector containing equally spaced grid of values.


Syntax: @grid(d1, d2, n)
d1: number
d2: number
n: integer
Return: vector

Returns a vector holding an arithmetic sequence of n elements. The initial element has value
d1, the last element is d2, and there are equal increments between rows of the vector.

Examples
vector v1 = @grid(0, 3, 10)

creates V1, a 10-element vector with first element 0, last element 3, and equal increments
between successive rows of the vector.
vector cdf1 = @cnorm(@grid(-2.0, 2.0, 401))

creates a 401-element vector of normal CDF ordinates evaluated at points from -2.0 to 2.0.

Cross-references
See also @seq (p. 1110) and @range (p. 1063).
898—Function Reference: G
@hcat—899

Function Reference: H
@hasoption...........Indicator for whether option is provided in the exec or run com-
mands (p. 899).
@hcat ...................Vertically concatenate matrices (p. 899).
@hmean ...............Harmonic mean (p. 900).
@holiday ..............Holiday identifier for observation (p. 901).
@holidayset ..........Multiple holiday identifiers for observation (p. 905).
@hour ..................Hour of the day of the observation (integer) (p. 910).
@hourf .................Hour of the date of the observation (floating point) (p. 910).

@hasoption Support Functions

Indicator for whether option is provided in the exec or run commands.


Syntax: @hasoption(str)
str: string
Return: boolean (0 or 1)

returns 1 or 0 depending on whether the specified option is or is not in the program options
provided in the exec (p. 444) or run (p. 581) command.

Cross-references
See exec (p. 444) and run (p. 581).

@hcat Matrix Utility

Vertically concatenate matrices.


Syntax: @hcat(m1, m2[, m3, ...])
m#: matrix, vector, svector or sym
Return: matrix

Performs vertical concatenation of two matrix objects. Each of the m# must have the same
number of columns.

The result will have the same number of rows and sum of the number of columns of the m#.

For example, if m1 is a matrix with m rows and k columns, and m2 is a matrix with m rows
and p columns, then @hcat will return a matrix with m rows and (k+p) columns.

Examples
vector v1 = @fill(1, 2, 3)
900—Function Reference: H

matrix k1 = @hcat(v1, 2*v1, 3*v1)

produces the matrix K1 which horizontally join the vectors V1, 2*V1 and 3*V1.
matrix g1 = @mnrnd(3, 3)
sym s1 = @identity(3)
matrix m1 = @hcat(g1, s1, v1)

horizontally joins the random normal matrix G1, the identity matrix, and the vector V1.

Cross-references
See also @vcat (p. 1182).

@hmean Basic Statistics

Harmonic mean.

Computes the harmonic mean of the elements of x.


Syntax: @hmean(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

The harmonic mean is calculated as


1
y  --------------------------
T
-
1
----  1  x t
T
t1

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x is a series of length 4 with elements 1, 2, 4, and 4, then
= @hmean(x)

returns 2 (= 4 divided by 2).

Cross-references
See also @mean (p. 971), @gmean (p. 896), and @trmean (p. 1154).
@holiday—901

@holiday Workfile Functions

Holiday identifier for observation.


Syntax: @holiday(h[, b][, flag...])
h: string
b: (optional) string
flag: (optional) string
Return: series

where h is the holiday event specification, b is a basis specification, and flag is a calculation
scaling flag.

Returns the proportion or identifier of an annual event covered by the observation, for each
observation in the workfile.

@holiday is similar to @holidayset (p. 905), but allows for the specification of holidays
using a range pair of dates, while disallowing multiple holiday event specifications.

Event Specification
The h specification identifies holiday events using date specifications of the form:
"base[~|!][(offset)][[weights]]"
where the base component consists of a single date, a pair of dates (forming a range), or a
single or a named group of holidays:
• A single date consists of either a non-space delimited day day-of-the-month specifica-
tion (e.g., “Dec25”), an n-th-weekday-of-the-month specification (e.g., “Nov4Thu” for
the fourth Thursday in November or “May-1Mon” for the last Monday in May, using
negative values for the last weekday in month, or a named holiday (“Named Holi-
days,” on page 902).
• Multiple dates may be specified using a date range (e.g., “Dec25 Jan05” and
“Nov4Thu May-1Mon”), or a named group of holidays (“Named Groups,” on
page 903).

The remainder of the specification consists of optional settings. The base component speci-
fication may be followed by any of the following options:
• a weekend modifier (“Modifiers,” on page 903).
• a parenthetical offset (“Offsets,” on page 904).
• a bracketed list of weights (“Weights,” on page 904).
902—Function Reference: H

For a base consisting of a range pair of dates, optional settings may be provided for both the
start and end dates.

For a base consisting of a named group, the optional settings will be applied to each of the
individual members of the group.
Named Holidays
EViews supports named holidays for common holidays in the G8 countries, including the
following ecclesiastical holidays: “epiphany”, “easterfriday”, “goodfriday”, “easter”, “easter-
monday”, “ascension”, “pentecost”, “whitmonday”, “assumption”, “allsaints”, “immacu-
late”, “christmas”, “saintstephen.

Also available are New Years Day (“nyd”, “newyear”, and “newyears”), Lunar New Year
(“cny”, “lny”, and “lunarnewyear”), International Women’s Day (“women” and “wom-
ens”), and International Men’s Day (“men” and “mens”).

Named holidays primarily associated with a specific country are suffixed with a locale code
following ISO 3166-1 alpha-2, i.e., the Internet country codes for top-level domains such as
“.ca” and “.de”. These named holidays are:

• Canada – “victoria.ca”, “discovery.ca”, “canada”, “civic.ca”, “labour.ca”, “thanks-


giving.ca” (also“thanks.ca”), “remembrance.ca”, “boxing.ca”
• France – “labour.fr”, “victory.fr”, “bastille.fr”, “armistice.fr”
• Germany – “labour.de”, “unity.de”
• Italy – “liberation.it”, “labour.it”, “republic.it”
• Russia – “christmas.ru”, “defender.ru”, “springlabour.ru”, “victory.ru”, “russia”,
“unity.ru”
• United Kingdom – “mayday.uk”, “springbank.uk”, “summerbank.uk”, “boxing.uk”
• United States of America – “mlk.us”, “presidents.us”, “memorial.us”, “indepen-
dence.us”, “labor.us”, “columbus.us”, “veterans.us”, “thanksgiving” (also “thanks”)

Note that the named holidays “canada”, “russia”, and “thanksgiving” do not include a suf-
fix, either to avoid redundancy or maintain compatibility with earlier versions of EViews.
Also note that “christmas.ru” is included to reflect the Russian Orthodox Church’s use of the
Julian calendar.

In general, a suffix may be safely added to any named holiday that does not already include
one, e.g. “christmas.us” or “nyd.it”. Unless noted above, such combinations do not alter the
nominal date of the holiday but may produce different results when combined with a week-
end modifier (“Modifiers,” on page 903).
@holiday—903

Named Groups
Named groups are preset collections of holidays. EViews currently supports a single named
group, “bank”, for each of the supported locales, i.e., “bank.ca”, “bank.fr”, “bank.de”, etc.,
allowing easy access to the common bank holidays.

The membership of these groups are:

• Canada, “bank.ca” – “nyd goodfriday victoria discovery canada civic labour thanks-
giving remembrance christmas boxing”
• France, “bank.fr” –“ nyd eastermonday labour victory ascension whitmonday bas-
tille assumption allsaints armistice christmas”
• Germany, “bank.de” – “nyd goodfriday eastermonday labour ascension whitmonday
unity christmas saintstephen”
• Italy, “bank.it” – “nyd epiphany easter eastermonday liberation labour republic
assumption allsaints immaculate christmas saintstephen”
• Russia, “bank.ru” – “nyd christmas defender womens springlabour victory russia
unity”
• United Kingdom, “bank.uk” – “nyd goodfriday eastermonday mayday springbank
summerbank christmas boxing”
• United States of America, “bank.us” – “nyd mlk presidents memorial independence
labor columbus veterans thanksgiving christmas”

All named group members have an implied suffix matching the group’s suffix. When using a
named group, the sum of proportion values within a year will equal the number of group
members (ignoring sample effects).
Modifiers
A weekend modifier character “~” or “!” indicates special handling of dates that fall on
weekends.
• If “~” is used, then the date will be adjusted to the nearest weekday. A date landing
on a Saturday is adjusted to the preceding Friday, and a date landing on a Sunday is
adjusted to the following Monday.
• If “!” is used with a named holiday, then a more sophisticated set of rules is used to
determine when the holiday will be observed, reflecting public holiday and bank hol-
iday conventions.

In some locales, holidays are observed according to the simple rule encapsulated by the “~”
modifier and thus the two modifiers will behave identically. For example, suppose we are
evaluating “christmas.us!” for the year 2021. That date lands on a Saturday and the holiday
will be observed on the preceding Friday, Dec. 24. However, if evaluating “christmas.uk!”
904—Function Reference: H

for the same year, weekend holidays are observed on the nearest following weekday in this
locale, thus the holiday will be observed on Monday, Dec. 27. Similarly, “boxing.uk!” will be
observed on Tuesday, Dec. 28.
Offsets
A date followed by a parenthetical offset will be adjusted by the given number of days. For
example, “christmas(-1)” could be used to specify Christmas Eve. If a weekend modifier is
also present, e.g. “christmas~(-1)”, the offset is applied after any adjustment made by the
modifier.
Basis
The optional basis parameter may be used to specify that only certain days of the week or
times of the day should be included as part of the holiday. This parameter has the format
"start_weekday-end_weekday[, start_time-end_time]"

e.g. “mon-thu” or “mon-sun,10am-4pm”.


Weights
A date followed by a bracketed list of weights is considered to occur over multiple days. The
specified weights determine the relative proportion of the holiday occurring on each day,
with the sum of proportions across all days within a year equaling one. The list must contain
an odd number of terms, with the middle term corresponding to the nominal date of the hol-
iday (after adjustment from any weekend modifier or offset).

For example, evaluating “christmas” for a daily workfile would return the value 1 for the
observation on Dec. 25 and the value 0 for all other observations in that year. Evaluating
“christmas[1,2,1]” would return the value 0.25 for the observation on Dec. 24, the value 0.5
for Dec. 25, and the value 0.25 for Dec. 26, returning the value 0 for all other observations.

Several named weight patterns are available as alternatives to explicit weight lists:

• “rampup(n)” – An increasing integer sequence of length n ending on the date. For


example, “[rampup(3)]” is equivalent to “[1,2,3,0,0]”.
• “rampdown(n)” – A decreasing integer sequence of length n beginning on the date.
For example, “[rampdown(3)]” is equivalent to “[0,0,3,2,1]”.
• “ramp(n)” –An increasing and then decreasing integer sequence centered on the
date. For example, “[ramp(3)]” is equivalent to “[1,2,3,2,1]”.

Note that weights may not be included when a pair of dates is used to specify a range.

Flag
The optional flag parameter supports two options, “binary” and “denorm”.
@holidayset—905

• If “binary” is specified, any non-zero value that would be returned is replaced by one,
thus forcing the function to return only zeros and ones. This flag is equivalent to the
expression “@holiday(...)>0”.
• If “denorm” is specified, then the default normalization steps for weighted dates
(dividing by the sum of weights) and sets or groups of holidays (dividing by the num-
ber of distinct holidays) are not performed.

For example, @holiday("christmas[1,2,1]") returns values 0.25, 0.5, and 0.25 on


sequential observations around Christmas, whereas @holiday("christmas[1,2,1]",
"denorm") would return values 1, 2, and 1.

Examples
@holiday("Jan1")
@holiday("Veterans.us(7)Thanksgiving.us")
@holiday("NewYears[1,2,0]")

Cross-references
See “Holiday Functions,” on page 313 for extensive discussion. See also @holidayset
(p. 905).

@holidayset Workfile Functions

Multiple holiday identifiers for observation.


Syntax: @holidayset(h[, b][, flag...])
h: string
b: (optional) string
flag: (optional) string
Return: series

where h is one or more holiday event specifications, b is a basis specification, and flag is a
calculation scaling flag.

Returns the proportion or identifier of multiple annual events covered by the observation,
for each observation in the workfile.

@holidayset is similar to @holiday (p. 901), but allows for more than one holiday event
specification, while disallowing the specification of holidays using a range pair of dates.

Event Specification
The h specification consists of one or more holiday events, each of which is a date specifica-
tions of the form:
906—Function Reference: H

"base[~|!][(offset)][[weights]]"
where the base component consists of a single date, a named holiday, or a named group of
holidays:
• A single date consists of either a non-spaced delimited day-of-the-month specification
(e.g., “Dec25”), an n-th-weekday-of-the-month specification (e.g., “Nov4Thu” for the
fourth Thursday in November or “May-1Mon” for the last Monday in May, using neg-
ative values for the last weekday in month), or a named holiday (“Named Holidays,”
on page 902).
• Multiple dates may be specified using named group of holidays (“Named Groups,” on
page 903).

The remainder of the specification consists of optional settings. The base component speci-
fication may be followed by any of the following options:
• a weekend modifier (“Modifiers,” on page 903).
• a parenthetical offset (“Offsets,” on page 904).
• a bracketed list of weights (“Weights,” on page 904).

For a base consisting of a named group, the optional settings will be applied to each of the
individual members of the group.
Named Holidays
EViews supports named holidays for common holidays in the G8 countries, including the
following ecclesiastical holidays: “epiphany”, “easterfriday”, “goodfriday”, “easter”, “easter-
monday”, “ascension”, “pentecost”, “whitmonday”, “assumption”, “allsaints”, “immacu-
late”, “christmas”, “saintstephen.

Also available are New Years Day (“nyd”, “newyear”, and “newyears”), Lunar New Year
(“cny”, “lny”, and “lunarnewyear”), International Women’s Day (“women” and “wom-
ens”), and International Men’s Day (“men” and “mens”).

Named holidays primarily associated with a specific country are suffixed with a locale code
following ISO 3166-1 alpha-2, i.e., the Internet country codes for top-level domains such as
“.ca” and “.de”. These named holidays are:

• Canada – “victoria.ca”, “discovery.ca”, “canada”, “civic.ca”, “labour.ca”, “thanks-


giving.ca” (also“thanks.ca”), “remembrance.ca”, “boxing.ca”
• France – “labour.fr”, “victory.fr”, “bastille.fr”, “armistice.fr”
• Germany – “labour.de”, “unity.de”
• Italy – “liberation.it”, “labour.it”, “republic.it”
@holidayset—907

• Russia – “christmas.ru”, “defender.ru”, “springlabour.ru”, “victory.ru”, “russia”,


“unity.ru”
• United Kingdom – “mayday.uk”, “springbank.uk”, “summerbank.uk”, “boxing.uk”
• United States of America – “mlk.us”, “presidents.us”, “memorial.us”, “indepen-
dence.us”, “labor.us”, “columbus.us”, “veterans.us”, “thanksgiving” (also “thanks”)

Note that the named holidays “canada”, “russia”, and “thanksgiving” do not include a suf-
fix, either to avoid redundancy or maintain compatibility with earlier versions of EViews.
Also note that “christmas.ru” is included to reflect the Russian Orthodox Church’s use of the
Julian calendar.

In general, a suffix may be safely added to any named holiday that does not already include
one, e.g. “christmas.us” or “nyd.it”. Unless noted above, such combinations do not alter the
nominal date of the holiday but may produce different results when combined with a week-
end modifier (“Modifiers,” on page 903).
Named Groups
Named groups are preset collections of holidays. EViews currently supports a single named
group, “bank”, for each of the supported locales, i.e., “bank.ca”, “bank.fr”, “bank.de”, etc.,
allowing easy access to the common bank holidays.

The membership of these groups are:

• Canada, “bank.ca” – “nyd goodfriday victoria discovery canada civic labour thanks-
giving remembrance christmas boxing”
• France, “bank.fr” –“ nyd eastermonday labour victory ascension whitmonday bas-
tille assumption allsaints armistice christmas”
• Germany, “bank.de” – “nyd goodfriday eastermonday labour ascension whitmonday
unity christmas saintstephen”
• Italy, “bank.it” – “nyd epiphany easter eastermonday liberation labour republic
assumption allsaints immaculate christmas saintstephen”
• Russia, “bank.ru” – “nyd christmas defender womens springlabour victory russia
unity”
• United Kingdom, “bank.uk” – “nyd goodfriday eastermonday mayday springbank
summerbank christmas boxing”
• United States of America, “bank.us” – “nyd mlk presidents memorial independence
labor columbus veterans thanksgiving christmas”
908—Function Reference: H

All named group members have an implied suffix matching the group’s suffix. When using a
named group, the sum of proportion values within a year will equal the number of group
members (ignoring sample effects).
Modifiers
A weekend modifier character “~” or “!” indicates special handling of dates that fall on
weekends.
• If “~” is used, then the date will be adjusted to the nearest weekday. A date landing
on a Saturday is adjusted to the preceding Friday, and a date landing on a Sunday is
adjusted to the following Monday.
• If “!” is used with a named holiday, then a more sophisticated set of rules is used to
determine when the holiday will be observed, reflecting public holiday and bank hol-
iday conventions.

In some locales, holidays are observed according to the simple rule encapsulated by the “~”
modifier and thus the two modifiers will behave identically. For example, suppose we are
evaluating “christmas.us!” for the year 2021. That date lands on a Saturday and the holiday
will be observed on the preceding Friday, Dec. 24. However, if evaluating “christmas.uk!”
for the same year, weekend holidays are observed on the nearest following weekday in this
locale, thus the holiday will be observed on Monday, Dec. 27. Similarly, “boxing.uk!” will be
observed on Tuesday, Dec. 28.
Offsets
A date followed by a parenthetical offset will be adjusted by the given number of days. For
example, “christmas(-1)” could be used to specify Christmas Eve. If a weekend modifier is
also present, e.g. “christmas~(-1)”, the offset is applied after any adjustment made by the
modifier.
Basis
The optional basis parameter may be used to specify that only certain days of the week or
times of the day should be included as part of the holiday. This parameter has the format
"start_weekday-end_weekday[, start_time-end_time]"

e.g. “mon-thu” or “mon-sun,10am-4pm”.


Weights
A date followed by a bracketed list of weights is considered to occur over multiple days. The
specified weights determine the relative proportion of the holiday occurring on each day,
with the sum of proportions across all days within a year equaling one. The list must contain
an odd number of terms, with the middle term corresponding to the nominal date of the hol-
iday (after adjustment from any weekend modifier or offset).
@holidayset—909

For example, evaluating “christmas” for a daily workfile would return the value 1 for the
observation on Dec. 25 and the value 0 for all other observations in that year. Evaluating
“christmas[1,2,1]” would return the value 0.25 for the observation on Dec. 24, the value 0.5
for Dec. 25, and the value 0.25 for Dec. 26, returning the value 0 for all other observations.

Several named weight patterns are available as alternatives to explicit weight lists:

• “rampup(n)” – An increasing integer sequence of length n ending on the date. For


example, “[rampup(3)]” is equivalent to “[1,2,3,0,0]”.
• “rampdown(n)” – A decreasing integer sequence of length n beginning on the date.
For example, “[rampdown(3)]” is equivalent to “[0,0,3,2,1]”.
• “ramp(n)” –An increasing and then decreasing integer sequence centered on the
date. For example, “[ramp(3)]” is equivalent to “[1,2,3,2,1]”.

Note that weights may not be included when a pair of dates is used to specify a range.

Flag
The optional flag parameter supports two options, “binary” and “denorm”.
• If “binary” is specified, any non-zero value that would be returned is replaced by one,
thus forcing the function to return only zeros and ones. This flag is equivalent to the
expression “@holidayset(...)>0”.
• If “denorm” is specified, then the default normalization steps for weighted dates
(dividing by the sum of weights) and sets or groups of holidays (dividing by the num-
ber of distinct holidays) are not performed.

For example, @holidayset("christmas[1,2,1]") returns values 0.25, 0.5, and 0.25 on


sequential observations around Christmas, whereas @holidayset("christmas[1,2,1]",
"denorm") would return values 1, 2, and 1.

Examples
@holiday("Jan1")
@holiday("Veterans.us(7)Thanksgiving.us")
@holiday("NewYears[1,2,0]")

Cross-references
See “Holiday Functions,” on page 313 for extensive discussion. See also @holiday (p. 901).
910—Function Reference: H

@hour Workfile Functions

Hour of the day of the observation (integer).


Syntax: @hour
Return: series

Returns the integer hour (0–23) associated with each observation in the workfile (e.g., 9:35
a.m. returns 9, and 5:15 p.m. returns 17).
• If the workfile is of lower than hourly frequency, all observations will be set to 0.
• If the workfile is undated, observations will be set to -1.

Examples
series dt = @hour
saves the hours of the day into the series DT.
The command
smpl if @hour >= 12
sets the sample to only use afternoons and evenings.

Cross-references
See also @day (p. 826), @hourf (p. 910), @minute (p. 978), @month (p. 983), @quarter
(p. 1059), @seas (p. 1109), @second (p. 1109), @weekday (p. 1192), and @year (p. 1223).

@hourf Workfile Functions

Hour of the day of the observation (floating point).


Syntax: @hourf
Return: series

Returns the floating point hour (0–23+, including fractional portions) associated with each
observation in the workfile (e.g., 9:30 a.m. returns 9.5, and 5:15 p.m. returns 17.25).
• If the workfile is of lower than hourly frequency, all observations will be set to 0.
• If the workfile is undated, observations will be set to -1.

Examples
series dt = @hourf
@hourf—911

saves the floating point hours of the day into the series DT.
The command
smpl if @hourf >= 12.5
sets the sample to only include observations after 12:30 p.m.

Cross-references
See also @day (p. 826), @hour (p. 910), @minute (p. 978), @month (p. 983), @quarter
(p. 1059), @seas (p. 1109), @second (p. 1109), @weekday (p. 1192), and @year (p. 1223).
912—Function Reference: H
@identity—913

Function Reference: I
@identity..............Identity matrix (p. 913)
@ifirst ..................Index of the first non-missing value in the vector or series (p. 914).
@iif ......................Recode values by condition (conditional value) (p. 915).
@ilast ...................Index of the last non-missing value in the vector or series (p. 915).
@imax..................Index of maximum value (p. 916).
@imaxes...............Indices of maximum value (multiple) (p. 917).
@imin ..................Index of minimum value (p. 918).
@imins .................Indices of minimum value (multiple) (p. 918).
@implode .............Creates sym from lower triangle of square matrix (p. 919).
@implodeu ...........Creates sym from upper triangle of square matrix (p. 920).
@inlist..................Dummy variable for observation value in list (p. 921).
@inner .................Inner product (p. 922).
@insert.................Insert string into string (p. 923).
@instr ..................Find position of substring in a string (p. 924).
@intercept ............Intercept from a trend regression (p. 925).
@inv ....................Reciprocal function (p. 925).
@inverse ..............Inverse of matrix (p. 926).
@isempty .............Test for empty string (p. 926).
@isna ...................Test for missing values (p. 927).
@isobject ..............Does object exist in active workfile page (p. 929).
@ispanel...............Is the current workfile page panel structured (p. 929).
@isperiod .............is this the first observation matching the specified period (p. 930).
@issingular...........Test matrix for singularity (p. 931).
@isvalidgroup.......Does the string represent a valid EViews group or auto-series
(p. 931).
@isvalidname .......Indicator for whether string represents a valid name for an EViews
object (p. 932).

@identity Matrix Utility

Identity matrix.
Syntax: @identity(n)
n: integer
Return: matrix

Returns a square n  n identity matrix.


914—Function Reference: I

Examples
matrix i4 = @identity(4)

creates a 4  4 identity matrix.


matrix k4 = @kronecker(@fill(1, 2, 3), @identity(4))

generates the 12  4 matrix formed by taking the Kronecker product of the 3 element vector
and the 4  4 identity matrix.
sym z = @inner(@mnrnd(3, 3))
matrix k3 = @kronecker(@scale(@identity(3), @mrnd(3, 1)), z)

creates a 9  9 block diagonal matrix where a block equals Z multiplied by a random uni-
form number.

Cross-references
See also @ones (p. 1018), @unitvector (p. 1169), and @zeros (p. 1225).

@ifirst Basic Statistics

Index of the first non-missing value in the data object.


Syntax: @ifirst(m)
m: data object
Return: scalar

Returns a scalar containing the index of the first non-missing value of the data object.The
series version uses the current workfile sample.

Examples
Let V be a vector of length 4 whose elements are NA, NA, 4.2, and 1.7. Then
= @ifirst(v)

returns 3.

Cross-references
See also @cfirst (p. 740), @clast (p. 748), @cifirst (p. 744), and @cilast (p. 745).

See also @first (p. 886), @last (p. 940), and @ilast (p. 915).
@ilast—915

@iif Element Functions

Recode values by condition (conditional value).


Syntax: @iif(s, x, y)
s: number
x: number or string
y: number or string
Return: number or string

Returns x if s is non-zero (true); otherwise returns y .

Typically s is specified using an expression with a boolean operator or function returning


(0, 1) values (e.g., “z > 3” or “z > w”), but any argument providing (0, non-zero) values is
sufficient.

Examples
= @iif(x<0,1,0)

returns 1 if x is negative, 0 otherwise.

Cross-references
See also @nan (p. 1009) and @recode (p. 1068).

@ilast Basic Statistics

Index of the last non-missing value in the data object.


Syntax: @ilast(m)
m: data object
Return: scalar

Returns a scalar containing the index of the last non-missing value of the data object. The
series version uses the current workfile sample.

Examples
Let V be a vector of length 4 whose elements are 8.6, 0.3, NA, and NA. Then
= @ilast(v)

returns 2.
916—Function Reference: I

Cross-references
See also @cfirst (p. 740), @clast (p. 748), @cifirst (p. 744), and @cilast (p. 745).

See also @first (p. 886), @last (p. 940), and @ifirst (p. 914).

@imax Basic Statistics

Index of maximum value.

Workfile or row index corresponding to the maximum of the elements of x.


Syntax: @imax(x[, s])
x: data object
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

Return the actual workfile or row indices corresponding to


y  x T 

where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.

For series calculations, EViews will use the current or specified workfile sample.

Examples
Let x be a series of length 5 whose elements are 1, 3, 5, 4, 2. Then
= @imax(x)

returns 3 the (non-unique) index corresponding to the value 5.

Cross-references
See also @max (p. 965), @imaxes (p. 917), @maxes (p. 966), @imin (p. 918), and @imins
(p. 918).
@imaxes—917

@imaxes Basic Statistics

Indices of maximums values (multiple).

Returns n workfile or row indices corresponding to the n-th maximums of the elements of x.
Syntax: @imaxes(x, n[, s])
x: data object
n: integer
Return: vector

If n is not an integer, the integer floor n will be used.

Return the actual workfile or row indices corresponding to


y   x  T – n  1 , x  T – n  2 , , x T 

where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.
The indices will be ordered from high to low of the corresponding values.

For series calculations, EViews will use the current or specified workfile sample.

Examples
Let x be a series of length 5 whose elements are 1, 3, 5, 4, 2, 5.

Then
= @imaxes(x, 1)

returns a vector containing (3, 6) the set of indices corresponding to the value 5.

Similarly
= @imaxes(x, 2)

returns a vector containing (3, 6, 4) the set of indices corresponding to the values 5 and 4.

Cross-references
See also @max (p. 965), @maxes (p. 966), @imin (p. 918), and @imins (p. 918).
918—Function Reference: I

@imin Basic Statistics

Index of minimum value.

Workfile or row index corresponding to the minimum of the elements of x.


Syntax: @imin(x[, s])
x: data object
s: (optional) sample string or object when x is a series or alpha and
assigning to a series
Return: number

Given the order statistics  x  1 , x  2 , , x  T   representing the data ordered from low to
high, we return the actual workfile or row index corresponding to
y  x 1 

where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.

For series calculations, EViews will use the current or specified workfile sample.

Examples
Let x be a series of length 5 whose elements are 1, 3, 5, 4, 2. Then
= @imin(x)

returns 1.

Cross-references
See also @min (p. 975), @mins (p. 976), @imins (p. 918), @max (p. 965), @imax (p. 916),
@imaxes (p. 917), @maxes (p. 966).

@imins Basic Statistics

Indices of n-th smallest values (multiple).

Returns workfile or row indices corresponding to the n-th minimum of the elements of x.
Syntax: @imins(x, n[, s])
x: data object
n: integer
Return: vector

If n is not an integer, the integer floor n will be used.


@implode—919

Return the actual workfile or row indices corresponding to


y   x  1 , x  2 , , x  n  

where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.

For series calculations, EViews will use the current or specified workfile sample.

Examples
Let x be a series of length 5 whose elements are 4, 2, 1, 4, 2, 5.

Then
= @imins(x, 1)

returns a vector containing (3) the set of indices corresponding to the value 1.

Similarly
= @imins(x, 2)

returns a vector containing (3, 2, 5) the set of indices corresponding to the values 5 and 4.

Cross-references
See also @mins (p. 976), @imins (p. 918), @min (p. 975), @imin (p. 918), @max (p. 965),
@imax (p. 916), @imaxes (p. 917), @maxes (p. 966).

@implode Matrix Utility

Create sym from lower triangle of square matrix


Syntax: @implode(m)
m: matrix
Return: sym

Forms a sym by copying the lower triangle of a square input matrix, m. Note that this func-
tion does not check for symmetry.

Examples
Let M be a (square) matrix object. Then
sym s = @implode(m)

creates S, a sym object whose lower triangle is identical to that of M.

Cross-references
See also @explode (p. 880) and @implodeu (p. 920).
920—Function Reference: I

@implodeu Matrix Utility

Create sym from upper triangle of square matrix


Syntax: @implodeu(m)
m: matrix
Return: sym

Forms a sym by copying the upper triangle of a square input matrix, m. Note that this func-
tion does not check for symmetry.

Examples
Let M be a (square) matrix object. Then
sym s = @implodeu(m)

creates S, a sym object whose upper triangle is identical to that of M.

Cross-references
See also @explode (p. 880) and @implode (p. 919).

@incr Matrix Utility

Increment rows or columns of matrix.


Syntax: @incr(m, v[,p])
m: matrix
v: vector, rowvector
p: (optional) number
Return: matrix

Increment the rows or columns of a matrix by the corresponding vector times p. By default,
p is equal to 1.
• If m is a matrix and v is a vector, increment each column of m by p times v.
• If m is a matrix and v is a rowvector, increment each column of m by p times v.

Examples
matrix x = @mrnd(5, 3)

creates a 5  3 matrix X filled with random normals.

The commands
@inlist—921

vector v1 = @fill(1, 2, 3, 4, 5)
matrix x1 = @incr(x, v1)

form X1 by taking X and adding the vector V1 to each column (which is equivalent to add-
ing 1 to the first row, 2 to the second, etc).

The commands
rowvector v2 = @transpose(@fill(1, 2, 3))
matrix x2 = @incr(x, v2, -1)

creates X2 by taking X and subtracting the rowvector V2 from each row (which is the equiv-
alent of subtracting 1 from the first column, 2 from the second, etc.),

Cross-references
See also @scale (p. 1108).

@inlist Element Functions

Dummy variable for observation value in list.


Syntax: @inlist(x, list)
x: number or string
list: number or string
Return: number
where list is a quoted, space delimited list of values.

Returns a dummy variable series equal to 1 for observations where x is equal to one of the val-
ues specified in list, and 0 otherwise.

Note that string comparisons are case sensitive.

Examples
series d1 = @inlist(x, "1 3 5 7 9")
creates a dummy variable that takes the value 1 where X equals 1, 3, 5, 7, or 9, and 0 other-
wise.
series d2 = @inlist(a, """no problem"" help")

creates a dummy variable that takes the value 1 for observations in A that equal “no prob-
lem” or “help”, and 0 otherwise.

Cross-references
See also @between (p. 725).
922—Function Reference: I

@inner Matrix Algebra

Inner product.
Series and Vectors
Computes the inner product of x and y.
Syntax: @inner(x[, y, s])
x: series, vector
y: (optional) series, vector
s: (optional) sample string or object when x and y are series and assign-
ing to series
Return: number

Computes
T
z   xt yt
t1

given x and the optional input y. If the optional argument is omitted, computes the inner
product of x with itself so that it is equivalent to @sumsq if the second argument omitted.

EViews will use the current or specified workfile sample.


Matrix
Syntax: @inner(x)
x: matrix, sym
Return: number

Computes the symmetric matrix


z  xx
Examples
If X and Y are series of length 5 whose elements are 1, 2, 3, 4, 5, and 6, 7, 8, 9, 10, respec-
tively, then
= @inner(x, y)

returns 130.

The commands
matrix m = @mnrnd(5, 7)
sym S = @inner(m)
@insert—923

creates a 5  7 matrix M filled with normal random variables and the 7  7 symmetric
matrix S containing MM .

Cross-references
See also @prod (p. 1042), @sum (p. 1135), and @sumsq (p. 1136).

@insert Element Functions | String Functions

Insert string into a string.


Syntax: @insert(str1, str2, n)
str1: string
str2: string
n: integer
Return: string

Inserts the string str2 into the string str1 at the position given by the integer n.

Examples
string sval1 = "I believe it can be done"
string sval2 = "not "
@insert("I believe it can be done", "not ", 16)
@insert(sval1, sval2, 16)
@insert(sval1, "not ", 16)

all return the string “I believe it cannot be done”.

If ALPHA1 is an alpha series,


alpha a1 = @insert(sval2, "not ", 5)

creates an alpha series with the contents of ALPHA1 with the string “not ” at position 5, for
each observation in the workfile sample.
alpha a2 = @insert(sval1, a1, ser1)

inserts SVAL1 into A1 using the integer positions given in the series SER1.

If SVEC1 is an svector,
svector s1 = @insert("(pretty please)", svec1, 10)

inserts “(pretty please) ” into SVEC at position 10.

Cross-references
See also @replace (p. 1070), @instr (p. 924), @rinstr (p. 1078), and @mid (p. 974).
924—Function Reference: I

@instr Element Functions | String Functions

Find position of substring in a string.


Syntax: @instr(str1, str2[, n])
str1: string
str2: string
n: integer
Return: integer

Finds the starting position of the n-th occurrence of the target string str2 in the string str1.

By default, the function returns the location of the first instance of str2 in str1, but you may
provide the optional integer n to change the occurrence.

If the target string is not found, @instr will return a 0.

Examples
string sval = "1.23415"
@instr("1.23415", "34")
@instr(sval, "34")

return the value 4, since the substring “34” appears beginning in the fourth character of the
base string.

If ALPHA1 is an alpha series,


series s1 = @instr(alpha1, "34", 2)

fills the series with the 2nd instance of the string “34” in each string in ALPHA1, for each
observation in the workfile sample.

If SVEC1 is an svector,
vector v1 = @instr(svec1, sval)

fills the vector with the location of the contents of the string SVAL for each element of
SVEC1.

Cross-references
See also @rinstr (p. 1078) for finding substrings starting from the end of the string, and
@mid (p. 974) for extracting substrings.
@inv—925

@intercept Basic Statistics

Intercept from trend regression.

Computes the intercept (or intercepts for panel data) of an OLS regression versus a constant
and an implicit time trend.
Syntax: @intercept(x[, s])
x: series
s: (optional) sample string
Return: series

EViews will use the current or specified workfile sample.

This function is panel aware.

Examples
series y = 2 + 3 * @trend + @nrnd
= @intercept(y)

The first line generates the series y using a simple linear regression model, where the sole
regressor is a time trend, the intercept is 2, and the slope coefficient is 3. The second line
returns the OLS estimate of the intercept term, and is approximately 2 in large samples.

Cross-references
See also @trendcoef (p. 1151).

@inv Element Functions

Reciprocal function.
Syntax: @inv(x)
x: number, series
Return: number, series

Returns 1  x of the scalar x , or 1  x of each value of x in the series.

For scalars and series only. To obtain the reciprocals of the elements of a matrix object use
@einv (p. 865).

For matrix inversion, see @inverse (p. 926).

Examples
show @inv(x)
926—Function Reference: I

returns a linked series whose elements are the reciprocal of those in the series x.

Cross-references
See also @einv (p. 865), @emult (p. 869), and @ediv (p. 861).

@inverse Matrix Algebra

Inverse of matrix.
Syntax: @inverse(m)
m: matrix, sym
Return: matrix, sym

Returns the inverse of a square matrix object or sym.

The inverse has the property that the product of the inverse and the source matrix and is the
identity matrix. The inverse of a matrix returns a matrix, while the inverse of a sym returns
a sym. Note that inverting a sym is much faster than inverting a matrix.

Examples
matrix m1 = @mrnd(500, 10)
sym s1 = @inner(m1)
matrix sinv = @inverse(s1)

generates a matrix of random normals, computes the inner product and then its inverse.

The following demonstrates the properties of the inverse,


matrix i1 = sinv * s1

where I1 is the identity matrix.

Cross-references
See also @det (p. 835), @issingular (p. 931), @pinverse (p. 1038), and @rank (p. 1063).

@isempty Element Functions | String Functions

Test for empty string.


Syntax: @isempty(arg)
arg: string
Return: number

Tests arg for an empty string.


@isna—927

Return value is an integer (0, 1). An argument which test as missing return a 1, and 0 other-
wise.

When used with series objects, the test is performed for every observation in the workfile
sample. Note that when used with string matrix objects, the comparison is a test of all of the
elements of the matrix, and will return 0 if any element is not empty. Element tests are avail-
able in @eisna (p. 865).

Equivalent to the more general @isna (p. 927) when applied to string data.

Examples
Define the string objects
string s1 = "abc"
string s2 = ""

Then
scalar b1 = @isempty("abc")
scalar b2 = @isempty(s1)

sets the scalar objects B1 and B2 to 0, while


scalar c1 = @isempty("")

sets C1 to 1.

If ALPHA1 is an alpha series,


series d1 = @isempty(alpha1)

tests ALPHA1 for an empty string for each observation in the workfile sample.
svector svec1 = @fill("abc", "abc", "")
scalar sc1 = @isempty(svec1)

returns 0, since the command is a full test of SC1 for missing values and returns a 0 if any
element is not equal.

Cross-references
See also @eisna (p. 865) and @isna (p. 927).

@isna Element Functions | String Functions

Test for missing value.


Syntax: @isna(arg)
arg: number or string
Return: number
928—Function Reference: I

Tests arg for a missing (NA) value or empty string.

Return value is an integer (0, 1). An argument which tests as missing returns a 1, and 0 oth-
erwise.

When used with series objects, the test is performed for every observation in the workfile
sample. Note that when used with matrix objects, the comparison is a missing value test of
all of the elements of the matrix, and will return 0 if any element is not missing. Element
tests are available in @eisna (p. 865)

Examples
The test
scalar f = @isna(NA)

returns the value 1, not an NA.

If SER1 is a numeric series,


series s2 = @isna(ser1)

tests SER1 for an empty string for each observation in the workfile sample.

Consider the comparison


vector v1 = @fill(1, 2, NA)
scalar f2 = @isna(v1)

evaluates the entire vector V1, and returns 0 since some of the elements of V1 are not miss-
ing. Define the string objects
string s1 = "abc"
string s2 = ""

Then
scalar b1 = @isna("abc")
scalar b2 = @isna(s1)

sets the scalar objects B1 and B2 to 0, while


scalar c1 = @isna("")

sets C1 to 1.

If ALPHA1 is an alpha series,


series d1 = @isna(alpha1)

tests ALPHA1 for an empty string for each observation in the workfile sample.
svector svec1 = @fill("abc", "abc", "")
scalar sc1 = @isna(svec1)
@ispanel—929

returns 0, since the command is a full test of SC1 for missing values and returns a 0 if any
element is not equal.

Cross-references
See also @eeqna (p. 862), @isempty (p. 926), @eqna (p. 873), and @neqna (p. 1010).

@isobject Support Functions

Syntax: @isobject(str)
str: string
Return: integer

Check for an object’s existence in the current workfile page. Returns a “1” if the object with
the name str exists in the current workfile, and a “0” if it does not exist.

Examples
scalar exists = @isobject("x")

Cross-references
See also @isvalidgroup (p. 931) and @getnextname (p. 895).

@ispanel Workfile Functions

Indicator for panel workfile page.


Syntax: @ispanel
Return: integer

Returns a 0 or 1 depending on whether the active workfile page is panel structured.

Examples
scalar ispanel = @ispanel

assigns the (0, 1) panel indicator to the scalar object ISPANEL.


series ids = @recode(@ispanel, @crossid, NA)

creates a series that contains the cross-section identifiers if a panel workfile, and NAs, if not.

Cross-references
See also @cellid (p. 737) and @crossid (p. 772).
930—Function Reference: I

@isperiod Workfile Functions

Is observation the first one matching the specified period?


Syntax: @isperiod(d)
d: string
Return: series

Returns a (0, 1) dummy variable for whether the observation is the first that matches the
specified date d.
• If the natural frequency of the date is greater than or equal to the frequency of the
workfile, then only the single observation that includes the date will be assigned a 1.
All other observations will be set to 0.
• If the natural frequency of the date is lower than the frequency of the workfile, then
only the first observation that is included in the date will be assigned the value of 1.
All other observations will be set to 0.

Examples
Suppose we create a quarterly workfile running from 2000q1 to 2022q4:
workfile q 2000 2022

Then the commands


series perm12 = @isperiod("2005m12")
series perm4 = @isperiod("2005q4")

will assign a 1 only to the 2000q4 observation since that is the only observation that con-
tains or matches the specified date.

If we use a lower frequency date,


series perm1 = @isperiod("2000")

will assign a 1 only to the 2000q1 observation, since it is the first workfile observation
included in the date.
@isvalidgroup—931

Cross-references
See also @dateval (p. 825) and @makedate (p. 960)

@issingular Matrix Algebra

Test matrix for singularity.


Syntax: @issingular(m)
m: matrix, sym
Return: integer

Returns “1” if the square matrix or sym, m, is singular, and “0” otherwise.

A singular matrix has a determinant of 0, and cannot be inverted.

Examples
matrix m1 = @mnrnd(1, 10)
sym s1 = @inner(m1)
= @issingular(s1)

returns 1 indicating that the inner product of M1 is singular (i.e., not invertible).

Cross-references
See also @det (p. 835), @issingular (p. 931), and @rank (p. 1063).

@isvalidgroup Support Functions

Syntax: @isvalidgroup(str)
str: string
Return: integer

Check for whether a string represents a valid specification for creating an EViews group or
auto-series. Returns a “1” if the expression is valid, and a “0” if it is not.

Examples
If your workfile contains the series X, Y and Z:
scalar a = @isvalidgroup("x y z")

will set A equal to 1,


scalar b = @isvalidgroup("log(x)")

will set B equal to 1, and


932—Function Reference: I

scalar e = @isvalidgroup("log(xy)")

will set E equal to 0 since XY is not a valid series in the workfile.

In contrast to the result in E,


scalar f = @isvalidgroup("log(x*y)")

is valid, since “LOG(X*Y)” is a valid series expression.

Cross-references
See also @isobject (p. 929).

@isvalidname Support Functions

Indicator for whether string represents a valid name for an EViews object.
Syntax: @isvalidname(str)
str: string
Return: integer

Returns a “1” if the name is valid, and a “0” if it is not.

Examples
!y = @isvalidname("ABC")
returns the value 1.
!y = @isvalidname("re!sult%")

returns the value 0.

Cross-references
See also @makevalidname (p. 962).
Function Reference: J—933

Function Reference: J
934—Function Reference: J
@kronecker—935

Function Reference: K
@kronecker ..........Kronecker product (p. 935).
@kurt ...................Kurtosis (p. 936).
@kurtsby..............Kurtosis for each specified group (p. 937).

@kronecker Matrix Utility

Kronecker product.
Syntax: @kronecker(m1, m2)
m1: matrix, vector, sym
m2: matrix, vector, sym
Return: matrix

Calculates the Kronecker product of the two matrix objects, m1 and m2.

The resulting matrix has a number of rows equal to the product of the numbers of rows of
the two matrix objects and a number of columns equal to the product of the numbers of col-
umns of the two matrix objects.

The elements of the resulting matrix consist of submatrices consisting of an element of the
first matrix object multiplied by the entire second matrix object.

Examples
matrix k4 = @kronecker(@fill(1, 2, 3), @ones(4, 4))

generates the 12  4 matrix formed by taking the Kronecker product of the 3 element vector
and the 4  4 matrix of ones. The matrix is a vertical concatenation of a 4  4 matrix of
ones, a 4  4 matrix of twos, and a 4  4 matrix of 3s.

Cross-references
See also @identity (p. 913) and @vec (p. 1183).
936—Function Reference: K

@kurt Basic Statistics

Kurtosis.

Computes the kurtosis of the elements of x.


Syntax: @kurt(x[, s])
x: numeric object
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

The kurtosis is calculated as


T 4
1 xt – x
y  ----
T   -------------
ĵ 

t1

where x is the sample mean, and ĵ is an estimator for the standard deviation that is based
on the biased estimator for the variance
T
1 2
ĵ  ----
T   xt – x 
t1

The kurtosis of the normal distribution is 3. If the kurtosis exceeds 3, the distribution is
peaked (leptokurtic) relative to the normal; if the kurtosis is less than 3, the distribution is
flat (platykurtic) relative to the normal.

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x = @nrnd, then
= @kurt(x)

returns a value close to 3 in large samples (since the normal distribution has a kurtosis of 3).

Cross-references
See also @mean (p. 971), @var (p. 1179), and @skew (p. 1113).
@kurtsby—937

@kurtsby By-Group Statistics

Kurtoses for each specified group.


Syntax: @kurtsby(x, y[y1, y2, ... yn, s])
x: series
y...yn: series, alpha
s: (optional) sample string or object
Return: series

Returns the kurtoses of x for each group defined by distinct values of the y.

EViews will use the current or specified workfile sample.

Examples
show @kurtsby(x, g1, g2)

produces a linked series of the by-group sample kurtoses of the series x, where members of
the same group have identical values for both g1 and g2.

Cross-references
See also @skewsby (p. 1114).
938—Function Reference: K
@lag—939

Function Reference: L
@lag .................. n-th order lag function (p. 939).
@last ....................The last non-missing value in the vector or series (p. 940).
@lastsby ...............Last non-missing value in a series for each specified group (p. 941).
@lasterrnum .........Last error number generated by a previously issued command
(p. 941).
@lasterrstr ............Last error message generated by a previously issued command
(p. 942).
@left ....................Left-hand characters in a string (p. 942).
@len.....................Length of a string (p. 943).
@length................Length of a string (p. 944).
@linepath .............Location of the program file currently being executed (p. 944).
@loadprgini ..........Variable name value in an “.ini” file (p. 945).
@localt .................Convert UTC (Coordinated Universal Time) to local time (p. 946).
@log.....................Natural logarithm function (p. 947).
log ........................Natural logarithm function (p. 947).
@log10 .................Base-10 logarithm function (p. 948).
@log1mexp...........Natural logarithm function of 1 minus exponential of argument
(p. 948).
@log1p .................Natural logarithm function of 1 plus argument (p. 949).
@log2pi ................Natural logarithm of 2p (p. 949).
@logcnorm ...........Natural logarithm of standard normal cumulative distribution
(p. 950).
@logit...................Logistic transform (p. 950).
@logx ...................Arbitrary base logarithm function (p. 951).
@lower.................Lowercase representation of a string, or lower triangular matrix of a
matrix (p. 951).
@ltrim ..................Trim left-whitespace from string (p. 953).
@lu ......................LU decomposition of a matrix (p. 954).

@lag Series Utility

n-th order lag function.


Syntax: @lag(x, n)
x: series, alpha, vector, svector, matrix object
n: series, alpha, vector, svector, matrix object
Return: series
940—Function Reference: L

Returns n-th order lag of the series, alpha, vector, svector, or columns of a matrix x. If n is not
an integer, the integer floor n will be used.

For a matrix x, the function will return a matrix of the same size with rows shifted down (or
up if n is negative) n places. Unavailable rows will be filled with NAs.

This function is panel aware.

Examples
series y = 0
smpl @first+1 @last
y = @lag(y, 1) + @nrnd
smpl @all

The series y is a random walk process that starts at 0.


matrix(5,4) A
rnd(A)
matrix B = @lag(A,2)

Matrix A will be a 5  4 matrix containing random uniform draws. Matrix B will have two
rows of NAs, followed by the first three rows of A.

Cross-references
See also d (p. 812).

@last Basic Statistics

The last non-missing value in the data object.


Syntax: @last(o)
o: data object
Return: number or string

Returns a vector containing the last non-missing value of the single column data object. The
series version uses the current workfile sample.

Examples
Let V be a vector of length 4 whose elements are 8.6, 0.3, NA, and NA. Then
= @last(v)

returns 0.3.
@lasterrnum—941

Cross-references
See also @cfirst (p. 740), @clast (p. 748), @cifirst (p. 744), and @cilast (p. 745).

See also @first (p. 886), @ifirst (p. 914), and @ilast (p. 915).

@lastsby Series Utility

Last non-missing value in a series for each specified group defined by distinct values.
Syntax: @lastsby(x, y[y1, y2, ... yn, s])
x: series, alpha
y1...yn series, alpha, group
s: (optional) sample string or object
Return: series, alpha

Last non-missing value in each distinct value group computed using the current workfile or
specified sample.

Examples
show @lastsby(x, g1, g2)

produces a linked series of the by-group last non-missing values of the series x, where mem-
bers of the same group have identical values for both g1 and g2.

Cross-references
See also @firstsby (p. 887).

@lasterrnum Support Functions

Last error number generated by a previously issued command.


Syntax: @lasterrnum
Return: integer

If a previous program line did not generate an error, the result will be a 0.

May only be used in a program.

Cross-references
See also @lasterrstr (p. 942).
942—Function Reference: L

@lasterrstr Support Functions

Last error message generated by the previously issued command.


Syntax: @lasterrstr
Return: string

If a program line did not generate an error, the result will be an empty string.

May only be used in a program.

Cross-references
See also @lasterrnum (p. 941).

@left Element Functions | String Functions

Left hand characters in a string.


Syntax: @left(str, n)
str: string
n: integer
Return: string

Returns a string containing n characters from the left end of str. If the string is shorter than n
characters, this function returns all of the characters in the source string.

Examples
The commands
string orig = "I did not do it"
string sc1 = @left("I did not do it", 5)
string sc2 = @left(orig, 5)

return the string objects SC1 and SC2 containing the string “I did”.

If ALPHA1 is an alpha series,


alpha a1 = @left(alpha1, 7)

returns the left-most 7 characters from the string values of ALPHA1 for each observation in
the workfile sample.

If SVEC1 is an string vector,


svector s1 = @left(svec1, 12)
@len—943

returns an svector containing 12 characters from the left end of each element of SVEC1.

Cross-references
See also @wleft (p. 1203), @right (p. 1075), and @mid (p. 974).

@len Element Functions | String Functions

Length of a string
Syntax: @len(str)
str: string,
Return: integer

Returns integer values for the length of the string str.

Equivalent to @length.

Examples
The commands
string orig = "I did not do it"
@len("I did not do it")
@len(orig)

return the value 15.

If ALPHA1 is an alpha series,


series s1 = @len(alpha)

returns the length of the string values of ALPHA1 for each observation in the workfile sam-
ple.

If SVEC1 is an string vector,


vector v1 = @len(svec1)

returns a vector containing the length of each element of SVEC1.

Cross-references
See also @length (p. 944).
944—Function Reference: L

@length Element Functions | String Functions

Length of a string.
Syntax: @length(str)
str: string
Return: integer

Returns integer values for the length of the string str.

Equivalent to @len.

Examples
The commands
string orig = "I did not do it"
@length("I did not do it")
@length(orig)

return the value 15.

If ALPHA1 is an alpha series,


series s1 = @length(alpha1)

returns the length of the string values of ALPHA1 for each observation in the workfile sam-
ple.

If SVEC1 is an string vector,


vector v1 = @length(svec1)

returns a vector containing the length of each element of SVEC1.

Cross-references
See also @length (p. 944).

@linepath Support Functions

Location of the program file currently being executed.


Syntax: @linepath
Return: string

If @linepath is being executed as a child program from a parent as part of an include or


exec statement, the string will return the location of the child program.
@loadprgini—945

Examples
If the program d:\myprogs\program1.prg has the line:
string y = @linepath

then y will contain “D:\MYPROGS\PROGRAM1.PRG”, no matter if program1 is run by itself,


or as part of another program.

Cross-references
See also @runpath (p. 1101), @evpath (p. 878) and @temppath (p. 1145).

@loadprgini Support Functions

Variable name value in an “.ini” file.


Syntax: @loadprgini("[section]name", "filename")
name: string
filename: string
section: (optional) string
Return: string

Returns a string containing the value of the specified variable name in the optionally speci-
fied section from the “.ini” file specified in filename. Both arguments must be enclosed in
quotes.

If filename is not specified the default “.ini” is the one with the name of the current running
program with extension “.ini.”

Note that the function returns a string, so to obtain a number you will have to convert the
string using @val.

Examples
string val = @loadprgini("[section1]a", "myini.ini")

will save the value of “a” retrieved from section [section1] of the “.ini” file “myini.ini”
located in your program file path.

Cross-references
See saveprgini (p. 583).
946—Function Reference: L

@localt Element Functions

Convert UTC (Coordinated Universal Time) to local time.


Syntax: @localt(utctime[, timezone])
utctime: date number, series, vector
timezone: (optional) timezone string
Return: date number, series, vector

Returns the local time zone representation of a point in time input in Coordinated Universal
Time (UTC), utctime.
• If timezone is not provided, the current Windows time zone setting is used as the local
time zone target.
• If timezone is provided, the timezone string can either contain raw time zone informa-
tion in the format returned by @tzspec (p. 1156) or it can contain search text (such as
a city name) found within one of the time zone descriptions returned by the function
@tzlist (p. 1155).

Examples
The commands
scalar dtime = @now
string london_spec = @tzspec("London")
@localtime(dtime, "+00:00 +01:00 Mar-1Sun 1:00 to Oct-1Sun 2:00")
@localtime(dtime, london_spec)
@localtime(dtime, "London")

give the date number for current London time. The first instance of @localtime uses the
raw string for the London timezone string.

If UTC1 is a series containing UTC time values,


series tokyo_time = @localt(utc1, "Tokyo")

converts the values into equivalent local time values in Tokyo, for all observations in the
workfile sample.

If UTC2 is a vector containing time values,


vector madrid_time = @localtime(utc2, "Madrid")

converts all date numbers in UTC2 into local Madrid time.

Additionally, if LOCSTR is a string vector containing timezone information


log—947

vector local_time = @localtime(@now, locstr)

converts the current time date number into the local time specified in the elements of LOC-
STR.

Cross-references
See “Dates,” on page 104 and “Event Functions,” on page 311 for related discussion.

See also the related time zone functions @utc (p. 1173), @tz (p. 1155), @tzlist (p. 1155),
and @tzspec (p. 1156).

@log Element Functions

Natural logarithm function.


Syntax: @log(x)
x: number
Return: number

Returns y  log e  x  for x  0 .

Examples
= @log(1.05)

returns 0.04879....

Cross-references
See log (p. 947), @log1mexp (p. 948), @log1p (p. 949), @log10 (p. 948), @logx (p. 951),
@log2pi (p. 949).

See also exp (p. 879) and @exp (p. 879).

log Element Functions

Natural logarithm function.


Syntax: log(x)
x: number
Return: number

Returns y  log e  x  for x  0 .

Examples
= log(1.05)
948—Function Reference: L

returns 0.04879....

Cross-references
See @log (p. 947), @log1mexp (p. 948), @log1p (p. 949), @log10 (p. 948), @logx (p. 951),
@log2pi (p. 949).

See also exp (p. 879) and @exp (p. 879).

@log10 Element Functions

Base-10 logarithm function.


Syntax: @log10(x)
x: number
Return: number

Returns y  log 10  x  for x  0 .

Examples
= @log10(100)

returns 2.

Cross-references
See log (p. 947) and @logx (p. 951), @log2pi (p. 949).

@log1mexp Element Functions

Natural logarithm function of 1 minus exponential of argument.


Syntax: @log1mexp(x)
x: number
Return: number
x
Returns y  log e  1 – e  .

Provides higher-precision calculation of the expression for negative x near 0 than direct
evaluation using
@log(1 - @exp(x))

Examples
= @log1mexp(-0.05)

returns -3.02062....
@log2pi—949

Cross-references
See @log (p. 947), @log1p (p. 949), @log10 (p. 948), @logx (p. 951), @log2pi (p. 949).

See also exp (p. 879) and @exp (p. 879).

@log1p Element Functions

Natural logarithm function of 1 plus argument.


Syntax: @log1p(x)
x: number
Return: number

Returns y  log e  1  x  .
Provides higher precision calculation of the expression for x near 0 than direct evaluation using
@log(1 + x)

Examples
= @log1p(0.05)

returns 0.04879....

Cross-references
See @log (p. 947),, @log1p (p. 949), @log10 (p. 948), @logx (p. 951), @log2pi (p. 949).

See also exp (p. 879) and @exp (p. 879).

@log2pi Numeric Constants

Natural logarithm of 2p .
Syntax: @log2pi
Return: number

Examples
= @log2pi

returns 1.83787....

Cross-references
See also @log (p. 947) and log (p. 947).
950—Function Reference: L

@logcnorm Element Functions

Natural logarithm of standard normal cumulative distribution.


Syntax: @logcnorm(x[, u])
x: number
u: (optional) number
Return: number

Computes the natural logarithm of the cumulative distribution integral


x
log F  x   log  f  s  ds
–

where
–1  2 2
f  s    2p  exp  – s  2 

If the optional argument u is non-zero, return the logarithm of the upper-tail cumulative dis-
tribution value: log  1 – F  x   .

Examples
= @logcnorm(-1.96)

returns -3.68896... (the natural log of 0.02499...).

Cross-references
See also @cnorm (p. 753), @dnorm (p. 845), @qnorm (p. 1054), and @rnorm (p. 1087).

@logit Element Functions

Logistic transform.
Syntax: @logit(x[, u])
x: number
u: (optional) number
Return: number

Computes the logistic function:


x
1 e
f  x   ----------------------  --------------
–x x
1  e  1e
If the optional argument u is non-zero, return the upper-tail value:
@lower—951

x
e 1
g  x   1 – --------------  --------------
x x
1e 1e
Examples
= @logit(.3)

returns 0.57444.
= @logit(.3, 1)

returns 0.42556.

Cross-references
See also @clogistic (p. 748), @dlogistic (p. 843), @qlogistic (p. 1052), and @rlo-
gistic (p. 1081).

@logx Element Functions

Arbitrary base logarithm function.


Returns the b-base logarithm of x.
Syntax: @logx(x, b)
x: number
b: number
Return: number

y  log b  x  for x, b  0 .
Examples
= @logx(256,2)

returns 8.

Cross-references
See also @log (p. 947), log (p. 947), @log1mexp (p. 948), @log1p (p. 949), @log10
(p. 948), and @log2pi (p. 949).

@lower Element Functions | String Functions | Matrix Utility

Lowercase representation of a string.


Syntax: @lower(str)
str: string, alpha, svector
Return: string, alpha, svector
952—Function Reference: L

Returns the lowercase representation of the string str.

Lower triangular matrix of a matrix.


Syntax: @lower(m[, n])
m: matrix, sym
n (optional) integer
Return: matrix

Returns a matrix whose elements on and below the n-th diagonal match the corresponding
elements of the matrix m, but whose elements above the n-th diagonal are zero.

By default, n is has a value of zero, indicating the main diagonal. Positive values of n indi-
cate super-diagonals, while negative values of k indicate sub-diagonals.

Examples
String
If we define the string object
string s1 = "I did NOT do it"

the commands
@lower("I did NOT do it")
@lower(s1)

return the string “i did not do it”.

If ALPHA1 is an alpha series,


alpha alphalwr = @lower(alpha1)

returns the lowercase of the strings in ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


svector sveclen = @lower(svec1)

returns a string vector containing the lowercased elements of SVEC1.


Matrix
The commands
matrix(3,3) m1
m1.fill 1, 2, 3, 4, 5, 6, 7, 8, 9
matrix l1 = @lower(m1)
matrix l2 = @lower(m1, 1)
matrix l3 = @lower(m1, -1)

create a 3  3 matrix M1
@ltrim—953

1 4 7
2 5 8
3 6 9

the matrix L1 containing,

1 0 0
2 5 0
3 6 9

the matrix L2 containing,

1 4 0
2 5 8
3 6 9

and the matrix L3 containing

0 0 0
2 0 0
3 6 0

If we have the commands,


sym s = @rwish(@identity(5), 5)
matrix s1 = @lower(s)
matrix s2 = @lower(s, -1)

then S is a 5  5 sym matrix and S1 is a 5  5 lower triangular matrix with elements at or


below the main diagonal equal to those in S, and elements below the main diagonal equal to
zero. S2 is a strictly lower triangular matrix that is equal to S1, but with the main diagonal
elements also set to 0.

Cross-references
See also @upper (p. 1171).

@ltrim Element Functions | String Functions

Trim left whitespace of a string.


Syntax: @ltrim(str)
tr: string, alpha, svector
Return: string, alpha, svector
954—Function Reference: L

Returns the string str with spaces trimmed from the left.

Examples
@ltrim(" I doubt that I did it. ")

returns “I doubt that I did it. ”. Note that the spaces on the right remain.

If ALPHA1 is an alpha series,


alpha alphaltrim = @ltrim(alpha1)

returns the left-trimmed strings in ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


svector sveclen = @ltrim(svec1)

returns a string vector containing the left-trimmed elements of SVEC1.

Cross-references
See also @rtrim (p. 1100) and @trim (p. 1153).

@lu Matrix Algebra

LU decomposition of matrix.
Syntax: @lu(M, L, U)
M: matrix
L: matrix
U: matrix
Return: matrix (P)

Performs an LU decomposition with partial (row) pivoting of the matrix M:


• if M is a square n  n produce a unit lower triangular matrix, L, an upper triangular
matrix, U, and a row permutation matrix, P, such that M  P  L  U .
• if M is a non-square m  n matrix, if m  n , L will be unit lower trapezoidal (rather
than triangular), and if m  n , U will be upper trapezoidal (rather than triangular).

Examples
matrix m = @mnrnd(10, 8)
matrix lmat
matrix umat
matrix pmat = @lu(m, lmat, umat)

generates the random matrix M, then performs the LU decomposition returning PMAT and
yielding updated LMAT, UMAT.
@lu—955

The following commands validate the definition


matrix m1 = pmat * lmat * umat
matrix diff = m - m1

since DIFF equals zero.

Cross-references
See also @cholesky (p. 743), @qr (p. 1055), @svd (p. 1137) and @svdfull (p. 1139).
956—Function Reference: L
Function Reference: M—957

Function Reference: M
@mae ...................Mean of absolute error (difference) between series (p. 959).
@makediagonal ....Create a matrix with vector placed on a diagonal (p. 961).
@makedate...........Convert numeric representation of a date to date number (p. 960).
@makevalidname .Make string into a valid EViews name (p. 962).
@mape .................Mean absolute percentage error (difference) between series
(p. 963).
@mav...................Trailing moving averages (ignore NAs) (p. 964).
@mavc .................Centered moving averages (ignore NAs) (p. 964).
@max...................Maximum value (p. 965).
@maxerrcount ......Maximum number of errors in a program before halting execution
(p. 966).
@maxes................Maximum values (multiple) (p. 966).
@maxsby..............Maximum values in a series for each specified group (p. 967).
@mcor..................Trailing moving correlations (ignore NAs) (p. 968).
@mcov .................Trailing moving population covariance (no d.f. adjustment; ignore
NAs) (p. 969).
@mcovp ...............Trailing moving population covariance (no d.f. adjustment; ignore
NAs) (p. 970).
@mcovs................Trailing moving sample covariance (d.f. adjusted; ignore NAs)
(p. 971).
@mean .................Arithmetic mean (p. 971).
@meansby ............Mean of observations in a series for each specified group (p. 972).
@median ..............Median (p. 973).
@mediansby .........Medians for a series for each specified group (p. 973).
@mid ...................Substring in middle or from middle to end of string (p. 974).
@min ...................Minimum value (p. 975).
@minner ..............Trailing moving inner product of two series (ignore NAs) (p. 976).
@mins..................Minimum values (multiple) (p. 976).
@minsby ..............Minimum values in a series for each specified group (p. 977).
@minute...............Minute of the hour of the observation (p. 978).
@mkurt ................Trailing moving kurtosis (ignore NAs) (p. 978).
@mmax ................Trailing moving maximums (ignore NAs) (p. 979).
@mmedian ...........Trailing moving median (ignore NAs) (p. 980).
@mmin ................Trailing moving minimums (ignore NAs) (p. 980).
@mnas .................Trailing moving missing observations (p. 981).
@mnrnd ...............Matrix of normal random numbers (p. 982).
@mobs .................Trailing moving non-missing observations (p. 982).
958—Function Reference: M

@mod .................. Floating point remainder (p. 983).


@month............... Month of the year of the observation (p. 983).
@movav .............. Trailing moving averages (propagate NAs) (p. 984).
@movavc ............. Centered moving averages (propagate NAs) (p. 985).
@movcor ............. Trailing moving population correlations (propagate NAs) (p. 986).
@movcov............. Trailing moving population covariance (no d.f. adjustment; propa-
gate NAs) (p. 987).
@movcovp ........... Trailing moving population covariance (no d.f. adjustment; propa-
gate NAs) (p. 988).
@movcovs ........... Trailing moving sample covariance (d.f. adjusted; propagate NAs)
(p. 989).
@movinner .......... Trailing moving inner product of two series (propagate NAs)
(p. 990).
@movkurt............ Trailing moving kurtosis (propagate NAs) (p. 990).
@movmax............ Trailing moving maximums (propagate NAs) (p. 991).
@movmedian....... Trailing moving median (propagate NAs) (p. 992).
@movmin ............ Trailing moving minimums (propagate NAs) (p. 992).
@movskew .......... Trailing moving skewness (propagate NAs) (p. 993).
@movstdev .......... Trailing moving sample standard deviations (d.f. adjusted; propa-
gate NAs) (p. 994).
@movstdevp ........ Trailing moving population standard deviations (non-d.f. adjusted;
propagate NAs) (p. 994).
@movstdevs......... Trailing moving sample standard deviations (d.f. adjusted; propa-
gate NAs) (p. 995).
@movsum............ Trailing moving sums (propagate NAs) (p. 996).
@movsumsq ........ Trailing moving sums of squares (propagate NAs) (p. 997).
@movvar ............. Trailing moving population variances (non d.f. adjusted; propagate
NAs) (p. 997).
@movvarp ........... Trailing moving population variances (non-d.f. adjusted; propagate
NAs) (p. 998).
@movvars............ Trailing moving sample variances (d.f. adjusted; propagate NAs)
(p. 999).
@mrnd ................ Matrix of uniform random numbers (p. 1000).
@mse................... Mean of square error (difference) between series (p. 1000).
@mskew .............. Trailing moving skewness (ignore NAs) (p. 1001).
@mstdev.............. Trailing moving sample standard deviation (d.f. adjusted; ignore
NAs) (p. 1002).
@mstdevp ............ Trailing moving population standard deviations (non-d.f. adjusted;
ignore NAs) (p. 1002).
@mae—959

@mstdevs .............Trailing moving sample standard deviations (d.f. adjusted; ignore


NAs) (p. 1003).
@msum ................Trailing moving sums (ignore NAs) (p. 1004).
@msumsq.............Trailing moving sums of squares (ignore NAs) (p. 1005).
@mvar .................Trailing moving population variances (non-d.f. adjusted; ignore
NAs) (p. 1005).
@mvarp................Trailing moving population variances (non-d.f. adjusted; ignore
NAs) (p. 1006).
@mvars ................Trailing moving population variances (d.f. adjusted; ignore NAs)
(p. 1007).

@mae Basic Statistics

Mean of absolute error (difference) between series.

Computes the mean of the absolute difference between x and y.


Syntax: @mae(x, y, [s])
x: series
y: series
s: (optional) sample string or object
Return: series
T
1
z t  ----
T  xt – yt
t1

EViews will use the current or specified workfile sample.

Examples
Let yf denote in-sample forecasts for the series y. Then
= @mae(yf, y)

returns the MAE between the series y and its forecast.

Cross-references
See also @mape (p. 963), @mse (p. 1000), @rmse (p. 1084), @smape (p. 1114), and @theil
(p. 1145).
960—Function Reference: M

@makedate Element Functions

Convert numeric representation of a date to date number.


Syntax: @makedate(arg1[, arg2[,arg3]], fmt)
arg1: number
args: (optional) number(s) arg2, arg3, ...
fmt: date format
Return: date number

Takes the numeric values given by the arguments arg1, and optionally, arg2, etc. and returns
a date number using the required format string, fmt.

If more than one argument is provided, the arguments must be listed from the lowest fre-
quency to the highest, with the first field representing either the year or the hour.

Examples
The expressions,
@makedate(1999, "yyyy")
@makedate(99, "yy")

both return the date number 729754.0 corresponding to 12 midnight on January 1, 1999.
@makedate(199003, "yyyymm")
@makedate(1990.3, "yyyy.mm")
@makedate(1031990, "ddmmyyyy")
@makedate(30190, "mmddyy")

all return the value 726526.0, representing March 1, 1990.

Dates may be created using multiple arguments. The expressions,


@makedate(97, 12, 3, "yy mm dd")
@makedate(1997, 12, 3, "yyyymmdd")

will return the value 729360.0 corresponding to midnight on December 3, 1997. You may
provide a subset of this information so that
@makedate(97, 12, "yymm")

returns the value 729358.0 representing the earliest date and time in December of 1997 (12
midnight, December 1, 1997). Likewise,
@makedate(1997, 37, "yyyy ddd")

yields the value 729060.0 (February 6, 1997, the 37th day of the year) and
@makediagonal—961

@makedate(14, 25, 10, "hh mi ss")

fills the series YM with date numbers for observations in the workfile sample.

If Y is a series containing year data, M is a series containing month data, and DT is a series
containing day data,
series ymd = @makedate(y, m, dt, "yyyymmdd")

fills the series YMDSTR with date numbers formed using those series, for observations in
the workfile sample.

Let MYDATE is a series that contains values with the year and month combined in a single
number (e.g., “201011”, “200505”),
mydate = y * 100 + m
series ym = @makedate(mydate, "yyyymm")

Then YM contains the date number associated with MYDATE.

If YVEC is a vector with (hour*10000 + minute*100 + seconds) values,


vector yearvec = @makedate(yvec, "hhmiss")

fills YEARVEC with the date numbers associated with each element of YVEC.

Cross-references
See “Date Formats” on page 106 and “Translating Ordinary Numbers into Date Numbers” on
page 116 for additional details.

See @datestr (p. 824) for string representations of date numbers.

@makediagonal Matrix Utility

Create a matrix with vector placed on a diagonal.


Syntax: @makediagonal(v[, k])
v: vector, rowvector
k: (optional) integer
Return: sym or matrix

Create a square matrix with v placed in the k-th diagonal relative to the main diagonal, and
zeros off the diagonal.
• If no k value is provided or if k is set to 0, the resulting sym matrix will have the same
number of rows and columns as the length of v, and will have v in the main diagonal.
962—Function Reference: M

• If a value for k is provided, the matrix has the same number of rows and columns as
the number of elements in the vector plus k, and will place v in the diagonal offset
from the main by k.

Examples
sym s1 = @makediagonal(v1)
matrix m2 = @makediagonal(v1,1)
matrix m4 = @makediagonal(r1,-3)

S1 will contain V1 in the main diagonal; M2 will contain V1 in the diagonal immediately
above the main diagonal; M4 will contain R1 in the diagonal 3 positions below the main
diagonal. Using the optional k parameter may be useful in creating covariance matrices for
AR models. For example, you can create an AR(1) correlation matrix by issuing the com-
mands:
matrix(10,10) m1
vector(9) rho = .3
m1 = @makediagonal(rho,-1) + @makediagonal(rho,+1)
m1 = m1 + @identity(10)

Note that to make a diagonal matrix with the same elements on the diagonal, you may use
@identity, multiplied by the scalar value.

Cross-references
See also @getmaindiagonal (p. 895) and @identity (p. 913).

@makevalidname Support Functions

Make string into a valid EViews name.


Syntax: @makevalidname(str)
str: string
Return: string

Returns a string containing an uppercased valid EViews name based on str.


• If str is a valid name, then the original string str is returned.
• If str exceeds the maximum length, the resulting string will be truncated.
• If str is not a valid name, invalid characters will be replaced in the new string with “_”
prior to the return.

Examples
@makevalidname("re!sult%")
@mape—963

returns the string “RE_SULT_”.


@makevalidname("evname01")

returns the string “EVNAME01”.

If ALPHA1 is an alpha series,


alpha a1 = @makevalidname(alpha1)

returns valid EViews names based on ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


svector sv1 = @makevalidname(svec1)

returns a string vector containing valid names corresponding to elements of SVEC1.

Cross-references
See also @isvalidname (p. 932) and @getnextname (p. 895).

@mape Basic Statistics

Mean absolute percentage error (difference) between series.

Computes the mean of the absolute percentage difference between x and y.


Syntax: @mape(x, y, [s])
x: series
y: series
s: (optional) sample string or object
Return: number
T
1 xt – yt
z t  100  ----
T  ---------------
yt
t1

EViews will use the current or specified workfile sample.

Examples
Let yf denote in-sample forecasts for the series y. Then
= @mape(yf, y)

returns the MAPE between the series y and its forecast.

Cross-references
See also @mae (p. 959), @mse (p. 1000), @rmse (p. 1084), @smape (p. 1114), and @theil
(p. 1145).
964—Function Reference: M

@mav Rolling (Moving) Statistics

Trailing moving averages (ignore NAs).

n-period trailing moving averages, ignoring NAs.


Syntax: @mav(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the average () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mav(x, 12)

produces a linked series of the moving average of the series x where NAs are ignored.

Cross-references
See also @mavc (p. 964) for a centered moving average.

For the NA-propagating variant of this function, see @movav (p. 984).

@mavc Rolling (Moving) Statistics

Centered moving averages (ignore NAs).

n-period centered moving averages, ignoring NAs.


Syntax: @mavc(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 ,


• If n is odd, compute the average of the current, and k previous and subsequent
observations of a series,
@max—965

 x t – k, , x t – 1, x t, x t  1, , x t  k 
where k   n – 1   2 . If missing values are encountered, the observation is dis-
carded, and the divisor for the mean is adjusted to compensate.
• If n is even, compute the n  1 period centered moving sum, weighting the end-
points by 1/2, then divide by n :
k
1   1 
y t  ---  
n  x t  j  ---  x t  m  x t – m  
 2
j  –k 
where k   n – 2   2 and m  n  2 . If missing values are encountered, the
observation is discarded, and the divisor for the mean is adjusted to compensate.

If n is not an integer, the integer floor n will be used.

Examples
show @mavc(x, 12)

produces a linked series of the centered moving average of the series x where NAs are
ignored.

Cross-references
See also @mav (p. 964) for a trailing moving average.

For the NA-propagating variant of this function, see @movavc (p. 985).

@max Basic Statistics

Maximum value.

Finds the maximum value of the elements of x.


Syntax: @max(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to
series
Return: number

The maximum may be written as


y  x T 

where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.

For series calculations, EViews will use the current or specified workfile sample.
966—Function Reference: M

Examples
Let x be a series of length 5 whose elements are 1, 3, 5, 4, 2. Then
= @max(x)

returns 5.

Cross-references
See also @imax (p. 916), @min (p. 975), and @maxes (p. 966).

@maxerrcount Support Functions

Maximum number of errors in a program before halting execution.


Syntax: @maxerrcount
Return: integer

Returns an integer containing the current value of the maximum number of errors that a
program may encounter before execution is halted.

May only be used in a program.

Cross-references
See also @errorcount (p. 877), setmaxerrs (p. 588), clearerrs (p. 393), seterr
(p. 587), and seterrcount (p. 587).

@maxes Basic Statistics

Maximum values (multiple).

Vector of the n maximum values of the elements of x.


Syntax: @max(x, n[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: vector

The maximum n values may be written as


y   x  T – n  1 , x  T – n  2 , , x T 

where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.

For series calculations, EViews will use the current or specified workfile sample.
@maxsby—967

Examples
Let x be a series of length 5 whose elements are 1, 3, 5, 4, 2. Then
= @maxes(x,2)

returns a vector of length 2 whose elements are 5 and 4.

Cross-references
See also @imaxes (p. 917), @mins (p. 976), and @max (p. 965).

@maxsby By-Group Statistics

Maximum values in a series for each specified group.


Syntax: @maxsby(x, y[y1, y2, ... yn, s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Returns the maximum value in x each group defined by distinct values of y.

EViews will use the current or specified workfile sample.

Examples
show @maxsby(x, g1, g2)

produces a linked series of the by-group maximums of the series x, where members of the
same group have identical values for both g1 and g2.

Cross-references
See also @minsby (p. 977).
968—Function Reference: M

@mcor Rolling (Moving) Statistics

Trailing moving correlations (ignore NAs).

n-period trailing moving Pearson product moment correlations between a pair of variables,
with d.f. correction, ignoring NAs.
Syntax: @mcor(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the correlations () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mcor(x, y, 12)

produces a linked series of the moving population correlation of the series x and y where
NAs are ignored.

Cross-references
See also @mcov (p. 969) for NA-excluding trailing moving covariances

For the NA-propagating variant of this function, see @movcor (p. 986).
@mcov—969

@mcov Rolling (Moving) Statistics

Trailing moving population covariance (no d.f. adjustment; ignore NAs).

n-period trailing moving Pearson product moment population covariances between a pair of
variables, with no d.f. correction, ignoring NAs.
Syntax: @mcov(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the population covariance () using the
current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movcov(x, y, 12)

produces a linked series of the moving population covariance of the series x and y where
NAs are ignored.

Cross-references
See also @mcovp (p. 970) and @mcovs (p. 971) for NA-excluding covariances.

For the NA-propagating variant of this function, see @movcov (p. 987).
970—Function Reference: M

@mcovp Rolling (Moving) Statistics

Trailing moving population covariance (no d.f. adjustment; ignore NAs).

n-period trailing moving Pearson product moment population covariances between a pair of
variables, with no d.f. correction, ignoring NAs.
Syntax: @mcovp(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the population covariance () using the
current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Equivalent to @mcov.

Examples
show @mcovp(x, y, 12)

produces a linked series of the moving population covariance of the series x and y where
NAs are ignored.

Cross-references
See also @mcov (p. 969) and @mcovs (p. 971).

For the NA-propagating variant of this function, see @movcovp (p. 988).
@mean—971

@mcovs Rolling (Moving) Statistics

Trailing moving sample covariance (d.f. adjusted; ignore NAs).

n-period trailing moving Pearson product moment sample covariances between a pair of
variables, with d.f. correction, ignoring NAs.
Syntax: @mcovs(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample covariance () using the cur-
rent and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mcov(x, y, 12)

produces a linked series of the moving sample covariance of the series x and y where NAs
are ignored.

Cross-references
See also @mcov (p. 969) and @mcovp (p. 970).

For the NA-propagating variant of this function, see @movcovs (p. 989).

@mean Basic Statistics

Arithmetic mean.

Computes the arithmetic mean of the elements of x.


Syntax: @mean(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number
972—Function Reference: M

T
1
y  ----
T  xt
t1

For series calculations, EViews will use the current or specified workfile sample.

Examples
= @mean(x)

returns the sample mean of a series x. If x = @rnd, then @mean(x) will be near 0.5 in
large samples.

Cross-references
See also @trmean (p. 1154), @gmean (p. 896), @hmean (p. 900), @median (p. 973), @var
(p. 1179), @skew (p. 1113), and @kurt (p. 936).

@meansby By-Group Statistics

Mean of observations in a series for each specified group defined by distinct values.
Syntax: @meansby(x, y[y1, y2, ... yn, s])
x: series
y1...yn series, alpha, group
s: (optional) sample string or object
Return: series

Compute the mean of observations in x for group identifiers defined by distinct values of y,
using the current or specified workfile sample.

Examples
show @meansby(x, g1, g2)

produces a linked series of by-group means of the series x, where members of the same
group have identical values for both g1 and g2.

Cross-references
See also @demeanby (p. 835).
@mediansby—973

@median Basic Statistics

Median.

Computes the median of the elements of x.


Syntax: @median(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

When T is odd, the median is the middle ordered-observation and when T is even, the
median is the average of the two middle ordered-observations. The median may be written
as

 xT  1   2 T is odd
y  
  x T  2   x T  2  1    2 T is even

where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.

For series calculations, EViews will use the current or specified workfile sample.

Examples
Let x be a series of length 6 with observations 1, 2, 3, 4, 5, 6. Then
= @median(x)

returns 3.5.

Cross-references
See also @mean (p. 971).

@mediansby By-Group Statistics

Medians for a series for each specified group defined by distinct values.
Syntax: @medians(x, y[y1, y2, ... yn, s])
x: series
y1...yn series, alpha, group
s: (optional) sample string or object
Return: series
974—Function Reference: M

Returns the median of x each group defined by distinct values of y, using the current or speci-
fied workfile sample.

Examples
show @mediansby(x, g1, g2)

produces a linked series of the by-group sample medians of the series x, where members of
the same group have identical values for both g1 and g2.

Cross-references
See also @meansby (p. 972) and @quantilesby (p. 1058).

@mid Element Functions | String Functions

Substring in middle or from middle to end of string.


Syntax: @mid(str, n1[, n2])
str: string, alpha, svector
n1: integer, series, vector
n2: (optional) integer, series, vector
Return: string, alpha, svector

Returns n2 characters from str, starting at location n1 and continuing for n2 characters to the
right. If you omit n2, it will return all of the remaining characters in the string.

Examples
The command
string s1 = @mid("I doubt it", 5)

assigns “ubt it” to the string object S1, while


string s2 = @mid("I doubt it", 5, 2)

assigns “ub” to S2.

If ALPHA1 is an alpha series,


alpha a1 = @mid(alpha1, 7)

returns the characters beginning with the 7th from the string values of ALPHA1 for each
observation in the workfile sample.

If LETTER_ID is a numeric series with integer values from 1 to 26, then


string alphabet = "abcdefghijklmnopqrstuvwxyz"
alpha letter = @mid(alphabet, letter_id, 1)
@min—975

will lookup the letter associated with each value of LETTER_ID for observations in the
workfile sample.

If SVEC1 is an string vector,


svector sv1 = @mid(svec1, 12, 5)

returns an svector beginning at the 12th for 5 characters for each element of SVEC1.

Cross-references
See also @wmid (p. 1206), @left (p. 942) and @right (p. 1075).

@min Element Functions

Minimum value.

Finds the minimum value of the elements of x.


Syntax: @min(x[, s])
x: data object
s: (optional) sample string or object when x is a series or alpha and
assigning to series or alpha
Return: number or string

The minimum may be written as


y  x 1 

where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.

For series calculations, EViews will use the current or specified workfile sample.

Examples
Let x be a series of length 5 whose elements are 1, 3, 5, 4, 2. Then
= @min(x)

returns 1.

Cross-references
See also @imin (p. 918), @mins (p. 976), and @max (p. 965).
976—Function Reference: M

@minner Rolling (Moving) Statistics

Trailing moving inner product of two series (ignore NAs).

n-period moving inner product of two variables for the current and previous n – 1 observa-
tions, ignoring NAs.
Syntax: @minner(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the inner product of the current and
previous n – 1 observations of the series,
n–1
zt   xt – j  yt – j
j0

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @minner(x, y, 12)

produces a linked series of the moving inner product of the series x and y where NAs are
ignored.

Cross-references
See also @msumsq (p. 1005).

For the NA-propagating variant of this function, see @movinner (p. 990).

@mins Basic Statistics

Minimum values (multiple).

Vector or svector the n minimum values of the elements of x.


Syntax: @mins(x, n[, s])
x: data object
s: (optional) sample string or object when x is a series or alpha
Return: vector or svector
@minsby—977

The minimum n values may be written as


y   x  1 , x  2 , , x  n  
where the order statistics  x  1 , x  2 , , x  T   represent the data ordered from low to high.
For series calculations, EViews will use the current or specified workfile sample.

Examples
Let x be a series of length 5 whose elements are 1, 3, 5, 4, 2. Then
= @mins(x,2)

returns a vector of length 2 whose elements are 1 and 2.

Cross-references
See also @imins (p. 918), @min (p. 975), and @maxes (p. 966).

@minsby By-Group Statistics

Minimum values in a series for each specified group.


Syntax: @minsby(x, y[y1, y2, ... yn, s])
x: series
y series or alpha
s: (optional) sample string or object
Return: series or alpha

Returns the minimum value in x each group defined by distinct values of y.

EViews will use the current or specified workfile sample.

Examples
show @minsby(x, g1, g2)

produces a linked series of the by-group minimums of the series x, where members of the
same group have identical values for both g1 and g2.

Cross-references
See also @maxsby (p. 967).
978—Function Reference: M

@minute Workfile Functions

Minute of the hour of the observation.


Syntax: @minute
Return: series

Returns the minute of the hour (0-59) associated with each observation in the workfile.
• If the workfile is of lower than minute frequency, all observations will be set to 0.
• If the workfile is undated, observations will be set to -1.

Examples
series dt = @minute
saves the minute of the hour into the series DT.
The command
smpl if @hourf >= 50
sets the sample to only include the last 10 minutes of each hour.

Cross-references
See also @day (p. 826), @hour (p. 910), @hourf (p. 910), @month (p. 983), @quarter
(p. 1059), @seas (p. 1109), @second (p. 1109), @weekday (p. 1192), and @year (p. 1223).

@mkurt Rolling (Moving) Statistics

Trailing moving kurtosis (ignore NAs).

n-period trailing moving kurtosis, ignoring NAs.


Syntax: @mkurt(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the average using the current and previ-
ous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.


@mmax—979

Examples
show @mkurt(x, 12)

produces a linked series of the moving kurtosis of the series x where NAs are ignored.

Cross-references
See also @mskew (p. 1001) for centered moving skewness.

For the NA-propagating variant of this function, see @movkurt (p. 990).

@mmax Rolling (Moving) Statistics

Trailing moving maximums (ignore NAs).


n-period trailing maximums, ignoring NAs.
Syntax: @mmax(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the maximum () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mmax(x, 12)

produces a linked series of maximums based on a 12-period moving window over the series
x where NAs are ignored.

Cross-references
See also @mmin (p. 980) for moving minimums.

For the NA-propagating variant of this function, see @movmax (p. 991).
980—Function Reference: M

@mmedian Rolling (Moving) Statistics

Trailing moving median (ignore NAs).

n-period trailing moving median, ignoring NAs.


Syntax: @mmedian(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the median using the current and previ-
ous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mmedian(x, 12)

produces a linked series of the moving median of the series X where NAs are ignored.

Cross-references
See also @mav (p. 964).

For the NA-propagating variant of this function, see @movmax (p. 991).

@mmin Rolling (Moving) Statistics

Trailing moving minimums (ignore NAs).

n-period trailing minimums, ignoring NAs.


Syntax: @mmin(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the minimum () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 
@mnas—981

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mmin(x, 12)

produces a linked series of minimums based on a 12-period moving window over the series
x where NAs are ignored.

Cross-references
See also @mmax (p. 979).

For the NA-propagating variant of this function, see @movmin (p. 992).

@mnas Rolling (Moving) Statistics

Trailing moving missing observations.

n-period trailing number of missing observations, ignoring NAs.


Syntax: @mnas(x, n)
x: series, alpha
n integer, series
Return: series

For each observation t and integer n  0 , count the number of missing (NA) observations
in the current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

Equivalent to @movnas.

Examples
show @mnas(x, 12)

produces a linked series of NA counts based on a 12-period moving window over the series
x.

Cross-references
See also @mobs (p. 982).
982—Function Reference: M

@mnrnd Matrix Utility

Matrix of normal random numbers.


Syntax: @mnrnd(n1[, n2])
n1: integer
n2: (optional) integer
Return: matrix

Creates a matrix filled with normal N  0, 1  random numbers. The size of the matrix is
given by the integers n1 (number of rows) and n2 (number of columns).

Examples
matrix m1 = @mnrnd(3,2)

creates a 3  2 matrix filled with standard normal random numbers.

If n2 is omitted or set to 1, the function returns a vector as in


vector v1 = @mnrnd(18)

You may obtain a random sym of normal numbers by creating a square source matrix of ran-
dom normals and assigning it to a sym matrix,
sym s1 = @mnrnd(5, 5)

which creates the sym S1 based on the lower triangle of the source matrix.

Cross-references
See also @mrnd (p. 1000), nrnd (p. 523), and rnd (p. 575).

@mobs Rolling (Moving) Statistics

Trailing moving non-missing observations.

n-period trailing number of non-missing observations, ignoring NAs.


Syntax: @mobs(x, n)
x: series, alpha
n integer, series
Return: series

For each observation t and integer n  0 , count the number of non-missing (non-NA)
observations in the current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 
@month—983

Equivalent to @movobs.

Examples
show @mobs(x, 12)

produces a linked series of non-NA counts based on a 12-period moving window over the
series x.

Cross-references
See also @mnas (p. 981).

@mod Element Functions

Floating point remainder.


Syntax: @mod(x, y)
x: number
y: number
Return: number

For non-zero y , returns the decimal remainder of x  y with the same sign as x
z  x–y xy
where . is the integer floor function.

If y  0 returns 0.

Examples
= @mod(4,3)

returns 1.

Cross-references
See also @round (p. 1088).

@month Workfile Functions

Month of the year of the observation.


Syntax: @month
Return: series

Returns the month of the year (1–12) associated with each observation in the workfile.
• If the workfile is of lower than monthly frequency, all observations will be set to 1.
984—Function Reference: M

• If the workfile is undated, observations will be set to -1.

Examples
series dt = @month
saves the month into the series DT.
The command
smpl if @month=12 or @month=1
sets the sample to only include observations in December and January.

Cross-references
See also @day (p. 826), @hour (p. 910), @hourf (p. 910), @minute (p. 978), @quarter
(p. 1059), @seas (p. 1109), @second (p. 1109), @weekday (p. 1192), and @year (p. 1223).

@movav Rolling (Moving) Statistics

Trailing moving averages (propagate NAs).

n-period trailing moving averages, propagating NAs.


Syntax: @movav(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the average () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movav(x, 12)

produces a linked series of the moving average of the series x where NAs are propagated.

Cross-references
See also @movavc (p. 985) for trailing moving averages.

For the NA-ignoring variant of this function, see @mav (p. 964).
@movavc—985

@movavc Rolling (Moving) Statistics

Centered moving averages (propagate NAs).

n-period centered moving averages, propagating NAs.


Syntax: @movavc(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 ,


• If n is odd, compute the average of the current, and k previous and subsequent
observations of a series, propagating missing values (NAs)
 x t – k, , x t – 1, x t, x t  1, , x t  k 
where k   n – 1   2 .
• If n is even, compute the n  1 period centered moving sum, weighting the end-
points by 1/2 and propagating missing values (NAs), then divide by n :
k
1   1 
y t  ---    x t  j  ---  x t  m  x t – m  
n  2 
j  –k

where k   n – 2   2 and m  n  2 .

If n is not an integer, the integer floor n will be used.

Examples
show @movavc(x, 12)

produces a linked series of the centered moving average of the series x where NAs are prop-
agated.

Cross-references
See also @movav (p. 984) for trailing moving averages.

For the NA-excluding variant of this function, see @mavc (p. 964).
986—Function Reference: M

@movcor Rolling (Moving) Statistics

Trailing moving population correlations (propagate NAs).

n-period trailing moving Pearson product moment population correlations between a pair of
variables, with d.f. correction, propagating NAs.
Syntax: @movcor(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the correlations () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movcor(x, y, 12)

produces a linked series of the moving population correlation of the series x and y where
NAs are propagated.

Cross-references
See also @movcor (p. 986) for moving correlation, and @movcov (p. 987) and @movcovs
(p. 989) for trailing moving covariances.

See @mcor (p. 968) for an NA-excluding version of this function.


@movcov—987

@movcov Rolling (Moving) Statistics

Trailing moving population covariance (no d.f. adjustment; propagate NAs).

n-period trailing moving Pearson product moment population covariances between a pair of
variables, with no d.f. correction, propagating NAs.
Syntax: @movcov(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the population covariance () using the
current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movcov(x, y, 12)

produces a linked series of the moving population covariance of the series x and y where
NAs are propagated.

Cross-references
See also @movcor (p. 986) for moving correlation, and @movcovp (p. 988) and @movcovs
(p. 989) for trailing moving covariances.

See @mcov (p. 969) for NA-excluding version of this function.


988—Function Reference: M

@movcovp Rolling (Moving) Statistics

Trailing moving population covariance (no d.f. adjustment; propagate NAs).

n-period trailing moving Pearson moment population covariances between a pair of vari-
ables, with no d.f. correction, propagating NAs.
Syntax: @movcovp(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the population covariance () using the
current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Equivalent to @movcov.

Examples
show @movcovp(x, y, 12)

produces a linked series of the moving population covariance of the series x and y where
NAs are propagated.

Cross-references
See also @movcovp (p. 988) and @movcovs (p. 989).

See @mcovp (p. 970) for NA-excluding version of this function.


@movcovs—989

@movcovs Rolling (Moving) Statistics

Trailing moving sample covariance (d.f. adjusted; propagate NAs).

n-period trailing moving Pearson product moment sample covariances between a pair of
variables, with d.f. correction, propagating NAs.
Syntax: @movcovs(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample covariance () using the cur-
rent and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movcov(x, y, 12)

produces a linked series of the moving sample covariance of the series x and y where NAs
are propagated.

Cross-references
See also @movcov (p. 987) and @movcovp (p. 988).

See @mcov (p. 969) for NA-excluding version of this function.


990—Function Reference: M

@movinner Rolling (Moving) Statistics

Trailing moving inner product of two series (propagate NAs).

n-period moving inner product of two variables for the current and previous n – 1 observa-
tions, propagating NAs.
Syntax: @movinner(x, y, n)
x: series
y: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the inner product of the current and
previous n – 1 observations of the series,
n–1
zt   xt – j  yt – j
j0

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movinner(x, y, 12)

produces a linked series of the moving inner product of the series x and y where NAs are
propagated.

Cross-references
See also @movsumsq (p. 997) for the trailing moving sums-of-squares.

See @minner (p. 976) for an NA-excluding version of this function.

@movkurt Rolling (Moving) Statistics

Trailing moving kurtosis (propagate NAs).

n-period trailing moving kurtosis, propagating NAs.


Syntax: @movkurt(x, n)
x: series
n integer, series
Return: series
@movmax—991

For each observation t and integer n  0 , compute the average () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movkurt(x, 12)

produces a linked series of the moving kurtosis of the series x where NAs are propagated.

Cross-references
See also @movskew (p. 993) for the trailing moving skewness.

See @mkurt (p. 978) for an NA-excluding version of this function.

@movmax Rolling (Moving) Statistics

Trailing moving maximums (propagate NAs).

n-period trailing maximums, propagating NAs.


Syntax: @movmax(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the maximum () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movmax(x, 12)

produces a linked series of maximums based on a 12-period moving window over the series
x where NAs propagate.

Cross-references
See also @movmin (p. 992).
992—Function Reference: M

For the NA-excluding variant of this function, see @mmax (p. 979).

@movmedian Rolling (Moving) Statistics

Trailing moving median (propagate NAs).

n-period trailing moving median, ignoring NAs.


Syntax: @movmedian(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the median using the current and previ-
ous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movmedian(x, 12)

produces a linked series of the moving median of the series X where NAs are propagated.

Cross-references
For the NA-excluding variant of this function, see @mmedian (p. 980).

@movmin Rolling (Moving) Statistics

Trailing moving minimums (propagate NAs).

n-period trailing minimums, propagating NAs.


Syntax: @movmin(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the minimum () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 
@movskew—993

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movmin(x, 12)

produces a linked series of minimums based on a 12-period moving window over the series
x where NAs propagate.

Cross-references
See also @movmax (p. 991).

@movskew Rolling (Moving) Statistics

Trailing moving skewness (propagate NAs).

n-period trailing moving skewness, propagating NAs.


Syntax: @movskew(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the average () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movskew(x, 12)

produces a linked series of the moving skew of the series x where NAs are propagated.

Cross-references
See also @movkurt (p. 990).

For the NA-ignoring variant of this function, see @mskew (p. 1001).
994—Function Reference: M

@movstdev Rolling (Moving) Statistics

Trailing moving sample standard deviations (d.f. adjusted; propagate NAs).

n-period trailing moving square roots of Pearson product moment sample variances, with
d.f. correction, propagating NAs.
Syntax: @movstdev(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample standard deviation () using
the current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movstdev(x, 12)

produces a linked series of the moving sample standard deviation of the series x where NAs
are propagated.

Cross-references
See also @movstdevp (p. 994), @movstdevs (p. 995), @movvar (p. 997), @movvarp
(p. 998), and @movvars (p. 999).

For the NA-ignoring variant of this function, see @mstdev (p. 1002).

@movstdevp Rolling (Moving) Statistics

Trailing moving population standard deviations (non-d.f. adjusted; propagate NAs).

n-period trailing moving square roots of (population) Pearson product moment population
variances, with no d.f. correction, propagating NAs.
Syntax: @movstdevp(x, n)
x: series
n integer, series
Return: series
@movstdevs—995

For each observation t and integer n  0 , compute the population standard deviation ()
using the current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movstdevp(x, 12)

produces a linked series of the moving population standard deviation of the series x where
NAs are propagated.

Cross-references
See also @movstdev (p. 994), @movstdevs (p. 995), @movvar (p. 997), @movvarp
(p. 998), and @movvars (p. 999).

For the NA-ignoring variant of this function, see @mstdevp (p. 1002).

@movstdevs Rolling (Moving) Statistics

Trailing moving sample standard deviations (d.f. adjusted; propagate NAs).

n-period trailing moving square roots of Pearson product moment sample variances, with
d.f. correction, propagating NAs.
Syntax: @movstdevs(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample standard deviation () using
the current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Equivalent to @movstdev.

Examples
show @movstdevs(x, 12)
996—Function Reference: M

produces a linked series of the moving sample standard deviation of the series x where NAs
are propagated.

Cross-references
See also @movstdev (p. 994), @movstdevp (p. 994), @movvar (p. 997), @movvarp
(p. 998), and @movvars (p. 999).

For the NA-ignoring variant of this function, see @mstdevs (p. 1003).

@movsum Rolling (Moving) Statistics

Trailing moving sums (propagate NAs).

n-period trailing moving sums, propagating NAs.


Syntax: @movsum(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sum () using the current and previ-
ous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movsum(x, 12)

produces a linked series of the moving sum of the series x where NAs are propagated.

Cross-references
See also @movsumsq (p. 997).

For the NA-ignoring variant of this function, see @msum (p. 1004).
@movvar—997

@movsumsq Rolling (Moving) Statistics

Trailing moving sums of squares (propagate NAs).

n-period trailing moving sums of squares, propagating NAs.


Syntax: @movsumsq(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sums of squares () using the current
and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movsumsq(x, 12)

produces a linked series of the moving sum of squares of the series x where NAs are propa-
gated.

Cross-references
See also @movsum (p. 996).

For the NA-ignoring variant of this function, see @msumsq (p. 1005).

@movvar Rolling (Moving) Statistics

Trailing moving population variances (non d.f. adjusted; propagate NAs).

n-period trailing moving Pearson product moment population variances, with no d.f. correc-
tion, propagating NAs.
Syntax: @movvar(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample variance () using the current
and previous n – 1 observations of the series,
998—Function Reference: M

 x t – n  1, , x t – 1, x t 

propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movvar(x, 12)

produces a linked series of the moving population variance of the series x where NAs are
propagated.

Cross-references
See also @movstdev (p. 994), @movstdevp (p. 994), @movstdevs (p. 995), @movvarp
(p. 998), and @movvars (p. 999).

For the NA-ignoring variant of this function, see @mvar (p. 1005).

@movvarp Rolling (Moving) Statistics

Trailing moving population variances (non-d.f. adjusted; propagate NAs).

n-period trailing moving Pearson product moment population variances, with no d.f. correc-
tion, propagating NAs.
Syntax: @movvarp(x, n)
x: series
n integer, series
Return: number

For each observation t and integer n  0 , compute the population variance () using the
current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Equivalent to @movvar.

Examples
show @movvarp(x, 12)

produces a linked series of the moving population variance of the series x where NAs are
propagated.
@movvars—999

Cross-references
See also @movstdev (p. 994), @movstdevp (p. 994), @movstdevs (p. 995), @movvar
(p. 997), and @movvars (p. 999).

For the NA-ignoring variant of this function, see @mvarp (p. 1006).

@movvars Rolling (Moving) Statistics

Trailing moving sample variances (d.f. adjusted; propagate NAs).

n-period trailing moving Pearson product moment sample variances, with d.f. correction,
propagating NAs.
Syntax: @movvars(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample variance () using the current
and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and propagating missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @movvars(x, 12)

produces a linked series of the moving sample variance of the series x where NAs are prop-
agated.

Cross-references
See also @movstdev (p. 994), @movstdevp (p. 994), @movstdevs (p. 995), @movvar
(p. 997), and @movvarp (p. 998).

For the NA-ignoring variant of this function, see @mvars (p. 1007).
1000—Function Reference: M

@mrnd Matrix Utility

Matrix of uniform random numbers.


Syntax: @mrnd(n1[, n2])
n1: integer
n2: (optional) integer
Return: matrix

Creates a matrix filled with uniform (0, 1) random numbers. The size of the matrix is given
by the integers n1 (number of rows) and n2 (number of columns).

Examples
matrix m1 = @mrnd(3,2)

creates a 3  2 matrix filled with uniform random numbers.

If n2 is omitted or set to 1, the function returns a vector as in


vector v1 = @mrnd(18)

You may obtain a random sym of uniform numbers by creating a square source matrix of
uniform numbers and assigning it to a sym matrix,
sym s1 = @mrnd(5, 5)

which creates the sym S1 based on the lower triangle of the source matrix.

Cross-references
See also @mnrnd (p. 982), nrnd (p. 523), and rnd (p. 575).

@mse Basic Statistics

Mean of square error (difference) of two series.

Computes the mean of the squared difference between x and y.


Syntax: @mse(x, y, [s])
x: series
y: series
s: (optional) sample string or object
Return: number
T
1 2
z t  ----
T   xt – yt 
t1
@mskew—1001

EViews will use the current or specified workfile sample.

Examples
Let yf denote in-sample forecasts for the series y. Then
= @mse(yf, y)

returns the MSE between the series y and its forecast.

Cross-references
See also @mae (p. 959), @mape (p. 963), @rmse (p. 1084), @smape (p. 1114), and @theil
(p. 1145).

@mskew Rolling (Moving) Statistics

Trailing moving skewness (ignore NAs).

n-period trailing moving skewness, ignoring NAs.


Syntax: @mskew(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the average () using the current and
previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mskew(x, 12)

produces a linked series of the moving skew of the series x where NAs are ignored.

Cross-references
See also @mkurt (p. 978) for moving kurtosis.

For the NA-propagating variant of this function, see @movskew (p. 993).
1002—Function Reference: M

@mstdev Rolling (Moving) Statistics

Trailing moving sample standard deviation (d.f. adjusted; ignore NAs).

n-period trailing moving square roots of Pearson product moment sample variances, with
d.f. correction, ignoring NAs.
Syntax: @mstdev(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample standard deviation (division
by n – 1 ) using the current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mstdev(x, 12)

produces a linked series of the moving sample standard deviation of the series x where NAs
are ignored.

Cross-references
See also @mstdevp (p. 1002), @mstdevs (p. 1003), @mvar (p. 1005), @mvarp (p. 1006), and
@mvars (p. 1007).

For the NA-propagating variant of this function, see @movstdev (p. 994).

@mstdevp Rolling (Moving) Statistics

Trailing moving population standard deviations (non-d.f. adjusted; ignore NAs).

n-period trailing moving square roots of Pearson product moment population variances,
with no d.f. correction, ignoring NAs.
Syntax: @mstdevp(x, n)
x: series
n integer, series
Return: series
@mstdevs—1003

For each observation t and integer n  0 , compute the population standard deviation ()
using the current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mstdevp(x, 12)

produces a linked series of the moving population standard deviation of the series x where
NAs are ignored.

Cross-references
See also @mstdev (p. 1002), @mstdevs (p. 1003), @mvar (p. 1005), @mvarp (p. 1006), and
@mvars (p. 1007).

For the NA-propagating variant of this function, see @movstdevp (p. 994).

@mstdevs Rolling (Moving) Statistics

Trailing moving sample standard deviations (d.f. adjusted; ignore NAs).

n-period trailing moving square roots of Pearson product moment sample variances, with
d.f. correction, ignoring NAs.
Syntax: @mstdevs(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample standard deviation () using
the current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Equivalent to @mstdev.

Examples
show @mstdevs(x, 12)
1004—Function Reference: M

produces a linked series of the moving sample standard deviation of the series x where NAs
are ignored.

Cross-references
See also @mstdev (p. 1002), @mstdevp (p. 1002), @mvar (p. 1005), @mvarp (p. 1006), and
@mvars (p. 1007).

For the NA-propagating variant of this function, see @movstdevs (p. 995).

@msum Rolling (Moving) Statistics

Trailing moving sums (ignore NAs).

n-period trailing moving sums, ignoring NAs.


Syntax: @msum(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sum () using the current and previ-
ous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @msum(x, 12)

produces a linked series of the moving sum of the series x where NAs are ignored.

Cross-references
See also @msumsq (p. 1005).

For the NA-propagating variant of this function, see @movsum (p. 996).
@mvar—1005

@msumsq Rolling (Moving) Statistics

Trailing moving sums of squares (ignore NAs).

n-period trailing moving sums of squares, ignoring NAs.


Syntax: @msumsq(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sums of squares () using the current
and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @msumsq(x, 12)

produces a linked series of the moving sum of squares of the series x where NAs are
ignored.

Cross-references
See also @msum (p. 1004).

For the NA-propagating variant of this function, see @movsumsq (p. 997).

@mvar Rolling (Moving) Statistics

Trailing moving population variances (non-d.f. adjusted; ignore NAs).

n-period trailing moving square roots of Pearson product moment population variances,
with no d.f. correction, ignoring NAs.
Syntax: @mvar(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the population variance () using the
current and previous n – 1 observations of the series,
1006—Function Reference: M

 x t – n  1, , x t – 1, x t 

ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mvar(x, 12)

produces a linked series of the moving population variance of the series x where NAs are
ignored.

Cross-references
See also @mstdev (p. 1002), @mstdevp (p. 1002), @mstdevs (p. 1003), @mvarp (p. 1006),
and @mvars (p. 1007).

For the NA-propagating variant of this function, see @movvar (p. 997).

@mvarp Rolling (Moving) Statistics

Trailing moving population variances (non-d.f. adjusted; ignore NAs).

n-period trailing moving square roots of population Pearson product moment variance, with
no d.f. correction, ignoring NAs.
Syntax: @mvarp(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the population variance () using the
current and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Equivalent to @mvar.

Examples
show @mvarp(x, 12)

produces a linked series of the moving population variance of the series x where NAs are
ignored.
@mvars—1007

Cross-references
See also @mstdev (p. 1002), @mstdevp (p. 1002), @mstdevs (p. 1003), @mvar (p. 1005), and
@mvars (p. 1007).

For the NA-propagating variant of this function, see @movvarp (p. 998).

@mvars Rolling (Moving) Statistics

Trailing moving population variances (d.f. adjusted; ignore NAs).

n-period trailing moving square roots of Pearson product moment sample variances, with
d.f. correction, ignoring NAs.
Syntax: @mvars(x, n)
x: series
n integer, series
Return: series

For each observation t and integer n  0 , compute the sample variance () using the current
and previous n – 1 observations of the series,
 x t – n  1, , x t – 1, x t 

and ignoring missing values (NAs).

If n is not an integer, the integer floor n will be used.

Examples
show @mvars(x, 12)

produces a linked series of the moving sample variance of the series x where NAs are
ignored.

Cross-references
See also @mstdev (p. 1002), @mstdevp (p. 1002), @mstdevs (p. 1003), @mvar (p. 1005), and
@mvarp (p. 1006).

For the NA-propagating variant of this function, see @movvars (p. 999).
1008—Function Reference: M
@nas—1009

Function Reference: N
@nan....................Recode missing values (p. 1009).
@nas ....................Number of missing observations (p. 1009).
@nasby ................Number of missing observations in a series or alpha for each speci-
fied group (p. 1010).
@neqna ................Inequality test (NAs and blanks treated as values, not missing)
(p. 1010).
@norm .................Norm of series or matrix object (p. 1012).
@now...................Current time date number (p. 1013).
@nper ..................Number of periods for annuity to pay given present value (p. 1013).

@nan Element Functions

Recode missing values.


Syntax: @nan(x, y)
x: number
y: number
Return: number

Returns x , if x is non-missing (not an NA or blank string); otherwise returns y .

Examples
show @pmax(x,-999)

returns a linked series that is identical to x except that NAs are replaced by the number -999.

Cross-references
See also @iif (p. 915), @recode (p. 1068), and @bridge (p. 727).

@nas Basic Statistics

Number of missing observations.

Number of missing (NA) observations in x .


Syntax: @nas(x[, s])
x: data object
s: (optional) sample string or object when x is a series or alpha and
assigning result to a series
Return: number
1010—Function Reference: N

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x is a series of length 5 with elements 1, NA, 2, NA, 3, then
= @nas(x)

returns 2.

Cross-references
See also @obs (p. 1015).

@nasby By-Row Statistics

Number of missing observations in a series or alpha for each specified group.


Syntax: @nasby(x, y[y1, y2, ... yn, s])
x: series, alpha
y series, alpha
s: (optional) sample string or object
Return: series

Compute the number of missing values in x for groups identifiers defined by distinct values
of y.

EViews will use the current or specified workfile sample.

Examples
show @nasby(x, g1, g2)

produces a linked series of by-group NA counts in the series x, where members of the same
group have identical values for both g1 and g2.

Cross-references
See also @obsby (p. 1016).

@neqna

Inequality test (NAs and blanks treated as values, not missing).


Syntax: @neqna(arg1, arg2)
arg1: number or string
arg2: number or string
Return: integer
@neqna—1011

Tests for inequality of arg1 and arg2, treating NA values and null strings as ordinary values
or blanks, and not as missing values. Simple inequality testing which propagates NAs may
be performed using the “<>” binary comparison operator.

Arguments which test as equal return a 0, and 1 otherwise.

When used with series objects, the test is performed for every observation in the workfile
sample. Note that when used with matrix objects, the comparison is an inequality test of all
of the elements of the two matrices, and will return 0 if any element comparison is false.
Individual element tests are available in @eneqna (p. 871)

Examples
The test
scalar f1 = @eqna(na, 2)

returns a 0, and not a missing value.

Consider the comparison


vector v1 = @fill(1, 2, 2)
scalar f2 = @neqna(v1, 2)

compares the entire vector V1 to 2, and returns 1 since some of the elements of V1 are equal
to 2. Note that this is a full inequality test that returns a 0 if any element is equal, and a 1 if
all elements are unequal (ignoring NAs)

If SER1 and SER2 are numeric series,


series s2 = @neqna(ser1, ser2)

tests SER1 and SER2 for inequality, ignoring NAs, for each observation in the workfile sam-
ple.

Define the string objects


string s1 = "abc"
string s2 = ""

Then
scalar b1 = @neqna("abc", "abc")
scalar b2 = @neqna("abc", s1)

sets the scalar objects B1 and B2 to 0, while


scalar c1 = @neqna("", "def")
scalar c2 = @neqna(s2, "def")
scalar c3 = @neqna(s1, s2)

sets C1, C2, and C3 to 1.


1012—Function Reference: N

If ALPHA1 and ALPHA2 are alpha series,


series d1 = @neqna(alpha1, "abc")
series d2 = @neqna(alpha1, s1)
series d3 = @neqna(alpha1, alpha2)

perform the inequality test using ALPHA1 and the literal string and scalar containing “abc”,
and the contents of ALPHA2 for each observation in the workfile sample.

If SVEC1 and SVEC2 are svectors,


scalar sc1 = @neqna(svec1, "abc")
scalar sc2 = @neqna(svec1, svec2)

perform the equality test of SVEC1 against “abc”, and the contents of SVEC2. Note that this
is a full inequality test of SVEC1 against the string, or against each element of SVEC2, and
that the test will return a 0 if any element is equal, and a 1 if all elements are unequal
(ignoring empty strings).

Cross-references
See also @eeqna (p. 862), @enisna (p. 872) and @eqna (p. 873).

@norm Matrix Utility

Norm of series or matrix object.


Syntax: @norm(m[, n])
m: numeric data object
n: (optional) integer
Return: number

Returns the norm of m.

If no norm type is provided, this function returns the infinity norm. Possible choices for the
norm type n include “–1” for the infinity norm, “0” for the Frobenius norm, and an integer
n
“n” for the L norm.

For series calculations, EViews will use the entire workfile. If you want to compute the norm
for a subsample, use mtos to convert the subsample of the series to a vector.

Examples
matrix m1 = @mnrnd(10, 4)
scalar sc1 = @norm(m1)

computes the infinity norm of the matrix M1.


sym s1 = @inner(m1)
@nper—1013

scalar sc2 = @norm(s1, 2)


2
computes the L norm of the symmetric matrix S1.
series x = nrnd
scalar sc3 = @norm(x)

assigns to SC3 the norm of the series X computed over the entire workfile.

@now Date Functions

Current time date number.


Syntax: @now
Return: date number

Returns the date number associated with the current time.

Examples
scalar nowtime = @now

Cross-references
See “Dates” on page 104 for additional details on date numbers and date format strings.

@nper Element Functions

Number of periods for annuity to pay given present value.


Syntax: @nper(r, x, pv[, v, bf])
r: number
x: number
pv: number
v: (optional) number
bf: (optional) number
Return: integer

Find the number of periods n required to receive at least the present value pv from an n-
period annuity, with receipts x and discount rate r, and optional receipt of a final lump sum v.

A non-zero value for the optional bf indicates that the receipts are made at the beginning of
periods (annuity due) instead of ends (ordinary annuity).
• The present value of by n-periods of ordinary annuity receipts and a final lump sum
is:
1014—Function Reference: N

n
1  r – 1 v
PVO  x  ----------------------------------  --------------------
n n
1  r r 1  r
• The present value of n-periods of annuity due receipts and a final lump sum is:
n
1  r – 1
 ---------------------------------
-  1  r – 1 
n
 r  v
PVD  x   ----------------------------------------------------------------------------   --------------------
n n
 1  r  1  r
 
Then for a given PVO or PVD and annuity type, the function returns the smallest n required
to exceed the required value.

Examples
= @nper(0.05, 100, 1000)

returns the value 14.20670, indicating that a 15-period annuity that pays $100 per period has
a present value greater than $1000 assuming the discount rate of 5%.

Cross-references
See also @fv (p. 889), @pmt (p. 1040), @pv (p. 1044), and @rate (p. 1066).
@obs—1015

Function Reference: O
@obs ....................Number of observations (p. 1015).
@obsby ................Number of non-missing observations in a series or alpha, for each
specified group (p. 1016).
@obsid .................Sequential index for the observation in the workfile (p. 1016).
@obsrange............Number of observations in the workfile page (p. 1017).
@obssmpl .............Number of observations in the workfile sample (p. 1017).
@ones ..................Matrix or vector of ones (p. 1018).
@option................Option string provided in the exec or run command (p. 1019).
@otod...................Workfile observation to date string (p. 1019).
@otods .................Sample observation to date string (p. 1020).
@outer .................Outer product of vectors or series (p. 1021).

@obs Basic Statistics

Number of observations.

Number of non-missing observations in x .


Syntax: @obs(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x is a series of length 5 with elements 1, NA, 2, NA, 3, then
= @obs(x)

returns 3.

Cross-references
See also @nas (p. 1009).
1016—Function Reference: O

@obsby By-Group Statistics

Number of non-missing observations in a series or alpha, for each specified group.


Syntax: @obsby(x, y[y1, y2, ... yn, s])
x: series, alpha
y series, alpha
s: (optional) sample string or object
Return: series

Compute the number of non-missing values in x for groups defined by distinct values of y.

EViews will use the current or specified workfile sample.

Examples
show @obsby(x, g1, g2)

produces a linked series of by-group non-NA counts in the series x, where members of the
same group have identical values for both g1 and g2.

Cross-references
See also @nasby (p. 1010).

@obsid Workfile Functions

Sequential index for observation in workfile.


Syntax: @obsid
Return: series

Return the sequentially assigned observation number for each observation in the workfile.

The observation index is panel aware. For panel workfiles, the observation numbers are not
associated with any particular value of within cross-section identifiers.

Examples
wfcreate a 2001 2022
series ids = @obsid

returns a series with sequential values 1 to 22.


smpl if @mod(@obsid, 5) = 0

sets the workfile sample to every fifth observation.


@obssmpl—1017

Cross-references
See also @obsrange (p. 705), @cellid (p. 737), and @crossid (p. 772).

@obsrange Workfile Functions

Number of observations in the current workfile page.


Syntax: @obsrange
Return: integer

Examples
scalar wflen = @obsrange

saves the workfile length in the scalar WFLEN.

The commands
smpl if @obsid < @obsrange*.8
equation eq1.ls y c x1 x2 x3
eq1.forecast(f=na, forcsmpl="if @obsid >= @obsrange*.8") eq1f

sets the sample to (approximately) the first 80% of the workfile sample, estimates an equa-
tion, then forecasts for the last 20% of the workfile.

Cross-references
See also @obssmpl (p. 1017) and @obsid (p. 600).

@obssmpl Workfile Functions

Number of observations in the current workfile sample.


Syntax: @obssmpl
Return: integer

Examples
The following set of commands
workfile u 1000
series y = nrnd
smpl if @abs(y) < 1.2
scalar trim = @obssmpl
1018—Function Reference: O

creates a workfile, sets a sample based on values of randomly generated Y then creates a
scalar object TRIM containing the number of Y observations with absolute values less than
1.2.

Cross-references
See also @obsrange (p. 1017) and @obsid (p. 600).

@ones Matrix Utility

Matrix or vector of ones.


Syntax: @ones(n1[, n2])
n1: integer
n2: (optional) integer
Return: matrix, vector

Creates a matrix or vector filled with the value 1. The size of the created matrix is given by
the integers n1 (number of rows) and n2 (number of columns).

Examples
matrix m1 = @ones(3,2)

creates M1, a 3  2 matrix of ones.


sym s1 = @ones(5, 5)
sym s2 = @unvech(@ones(5*6/2))

create 5  5 symmetric matrices of ones, while


vector v1 = @ones(18)

is an 18-element vector of ones, and


matrix k4 = @kronecker(@fill(1, 2, 3), @ones(4, 4))

generates the 12  4 matrix formed by taking the Kronecker product of a column vector
whose elements are 1, 2, and 3, and a 4  4 matrix of ones.

Cross-references
See also @identity (p. 913), @unitvector (p. 1169), and @zeros (p. 1225).
@otod—1019

@option Support Functions

Option string in an exec or run command.


Syntax: @option(arg)
arg: integer
Return: string

returns the i-th option provided in the exec (p. 444) or run (p. 581) command.

Cross-references
See exec (p. 444) and run (p. 581).

@otod Workfile Functions

Workfile observation to date string.


Syntax: @otod(n)
n: integer
Return: string

Returns a string identifying the date or observation corresponding to observation number n,


counted from the beginning of the current workfile. Invalid inputs will produce an empty
string.

EViews will use the global default settings for the Month/Day order in dates to determine
the ordering of days and months in the resulting date string.

Examples
For example, consider the string assignment
@otod(5)

For an annual workfile dated 1991–2000, the function returns the string “1995”. For a quar-
terly workfile dated 1970q1–2000q4, the function returns “1971q1”.
@otod(1)

returns the date or observation label for the start of the workfile.

If the series DSER contains integer workfile observation numbers,


alpha aser = @dtoo(dser)

fills ASER with string dates corresponding to the workfile observation numbers for each
observation in the workfile sample.
1020—Function Reference: O

If DVEC is a a vector containing integer observations numbers, the command


vector avec = @dtoo(dvec)

fills AVEC with the date strings corresponding to the workfile observation numbers in DVEC.

Cross-references
See also @otods (p. 1020) and @dtoo (p. 847).

@otods Workfile Functions

Sample observation to date string.


Syntax: @otods(n)
n: integer, series, vector
Return: string, alpha, svector

Returns a string containing the date or observation corresponding to observation number n,


counted from the beginning of the current workfile sample.

EViews will use the global default settings for the Month/Day order in dates to determine
the ordering of days and months in the resulting date string.

Examples
Thus
@otods(2)

will return the date associated with the second observation in the current sample. Note that
if n is negative, or is greater than the number of observations in the current sample, an
empty string will be returned.

If the series DSER contains integer sample observation numbers,


alpha aser = @otods(dser)

fills ASER with string dates corresponding to the given numbers for each observation in the
workfile sample.

If DVEC is a vector containing integer observation numbers, the command


vector avec = @otods(dvec)

fills AVEC with the date strings corresponding to the workfile observation numbers in DVEC.

Cross-references
See also @otod (p. 1019) and @dtoo (p. 847).
@outer—1021

@outer Matrix Utility

Outer product of vectors or series.


Syntax: @outer(v1, v2)
v1: vector, series
v2: vector, series
Return: matrix

Returns the outer product of the two vectors or series. If used with two vectors, @outer
requires that v1 and v2 be the same size.
• If used with two series, @outer returns a square matrix of every possible product of
the elements of the two inputs. For series calculations, EViews will use the entire
workfile.
• If used with two vectors, @outer computes v1  v2 . If v1 and v2 are column vectors,
the result is the square matrix of every possible product of the elements of the two
inputs. If v1 and v2 are row vectors, the result is a scalar containing the sum of the
element products.

Examples
vector v1 = @fill(1, 2, 3)
vector v2 = @fill(4, 5, 6)
matrix m1 = @outer(v1, v2)

produces a 3  3 outer product matrix M1,


workfile u 100
series x = nrnd
series y = nrnd
matrix m2 = @outer(x, y)

creates an undated workfile with 100 observations, two series of IID standard normal num-
bers X and Y, and a 100  100 outer product matrix M1.

If you wish to compute the outer product of two series objects for a subset of observations,
you will first have to extract the data to a sub-vector:
smpl 1 10
stom(x, vx)
stom(y, vy)
matrix m3 = @outer(vx, vy)
matrix m4 = m2.@sub(@range(1, 10), @range(1, 10))
1022—Function Reference: O

produces identical 10  10 outer products for the first 10 observations in the workfile in M3
and M4.

Cross-references
See also @inner (p. 922) and @qform (p. 1049).
Function Reference: P—1023

Function Reference: P
@pagecount ..........Number of pages in workfile (p. 1024).
@pageexist ...........Does a page exist in the workfile (p. 1024).
@pagefreq ............Frequency specification for the workfile page (p. 1025).
@pageids ..............Workfile page observation identifiers (p. 1026).
@pageidx..............Index vector of the specified observations (p. 1027).
@pageinidx...........Indicators for whether each observation in the workfile page is in
an index (p. 1028).
@pagelist..............List of pages in workfile (p. 1028).
@pagename ..........Name of active workfile page (p. 1029).
@pagerange ..........Range specification of active workfile page (p. 1029).
@pagesmpl ...........Sample specification in active workfile page (p. 1030).
@pagesmplidx ......Index vector of observations in the current sample (p. 1030).
@pc......................One-period percentage change (in percent) (p. 1031).
@pca ....................One-period percentage change, annualized (in percent) (p. 1031).
@pccagr ...............Annualized growth rate (in percent) (p. 1032).
@pch....................One-period percentage change (in decimal fraction) (p. 1033).
@pcha ..................One-period percentage change, annualized (in decimal fraction)
(p. 1033).
@pchy ..................One-year percentage change (in decimal fraction) (p. 1034).
@pctiles................Percentile values (p. 1035).
@pcy ....................One-year percentage change, (in percent) (p. 1036).
@periodtodate.......Within-period cumulative sum (period-to-date) (p. 1036).
@permute.............Permutation of matrix (p. 1037).
@pi ......................Pi – ratio of a circle's circumference to its diameter ( p ) (p. 1037).
@pinverse.............Moore-Penrose pseudo-inverse of matrix (p. 1038).
@pmax .................Pairwise maximum (p. 1039).
@pmin .................Pairwise minimum (p. 1039).
@pmt ...................Payment amount required for annuity to pay given present value
(p. 1040).
@pow...................Power function (p. 1041).
@pow1pm1 ..........Power function of 1 plus argument, minus 1 (p. 1041).
@powm1 ..............Power function, minus 1 (p. 1042).
@prod ..................Product (p. 1042).
@psi .....................First derivative of the natural log of the gamma function (p. 1043).
@pv......................Present value of annuity receipts and (optional) final lump sum
receipt (p. 1044).
1024—Function Reference: P

@pagecount Support Functions

Number of pages in the workfile.


Syntax: @pagecount
Return: integer

Returns the number of pages in the current workfile.

Examples
scalar pgs = @pagecount

Cross-references
See also @pageexist (p. 1024) and @pagelist (p. 1028).

@pageexist Support Functions

Indicator for whether a page exists in the workfile.


Syntax: @pageexist(str)
str: string
Return: integer

Returns a 0 or 1 depending on whether the page specified by str exists in the current work-
file.

Examples
The command
scalar pgs = @pageexist("Monthly")

creates a scalar that takes the value 1 if there is a page in the default workfile named
“Monthly”.
if (@pageexist("Quarterly") = 1) then
pageselect Quarterly
endif

tests for whether the page “Quarterly” exists in the workfile, and if it does, makes it the
active page.

Cross-references
See also @pagecount (p. 1024) and @pagelist (p. 1028).
@pagefreq—1025

@pagefreq Support Functions

Frequency of the current workfile page.


Syntax: @pagefreq
Return: string

Returns a string containing the frequency of the active page:


“Sec”, “5Sec”, Seconds in intervals of: 1, 5, 15, or 30 seconds, respec-
“15Sec”, “30Sec” tively, with optionally specified days of the week and start
and end times during the day appended in parentheses.
“Min”, “2Min”, Minutes in intervals of: 1, 2, 5, 10, 15, 20, or 30 minutes,
“5Min”, “10Min”, respectively, with optionally specified days of the week and
“15Min”, “20Min”, start and end times during the day appended in parenthe-
“30Min” ses.
“H”, “2H”, “4H”, Hours in intervals of: 1, 2, 4, 6, 8, or 12 hours, respec-
“6H”, “8H”, “12H” tively.with optionally specified days of the week and start
and end times during the day appended in parentheses.
“D(s, e)” Daily with arbitrary days of the week. Specify the first and
last days of the week with integers s and e, where Monday
is given the number 1 and Sunday is given the number 7.
“D5” Daily with five days per week, Monday through Friday.
“D7” Daily with seven days per week.
“W” Weekly
“T” Ten-day (daily in intervals of ten).
“F” Fortnight
“BM” Bimonthly
“M” Monthly
“Q” Quarterly
“S” Semi-annual
“A” Annual
“2Y”, “3Y”, “4Y”, Multi-year in intervals of: 2, 3, 4, 5, 6, 7, 8, 9, 10, or 20
“5Y”, “6Y”, “7Y”, years, respectively.
“8Y”, “9Y”, “10Y”,
“20Y”
1026—Function Reference: P

Examples
The command
string frq = @pagefreq

saves the frequency string in the string object FRQ.

The program commands


%frq = @pagefreq
pagecreate(page="newpage") {%frq} 2015 2023

extracts a string with the frequency of the active workfile page, then uses the frequency
information to create a new page named “Newpage” with observations from 2015 to 2023
using the same frequency.

Cross-references
See also @pageids (p. 1026), wfcreate (p. 634), and pagecreate (p. 540).

@pageids Support Functions

Workfile page observation identifier series.


Syntax: @pageids
Return: string

Returns a string containing a space delimited list of the observation identifier series for the
current workfile page.

Examples
workfile a 2010 2023
string id = @pageids

extracts the identifier string from the workfile. As with other standard structured workfiles
of this type, ID contains "@DATE".

For a dated panel workfile with date identifier YEAR, and cross section identifier series
COUNTRY,
string ids = @pageids

returns the string variable IDS containing “YEAR COUNTRY”.

Cross-references
See also @pagefreq (p. 1025), wfcreate (p. 634), and pagecreate (p. 540).
@pageidx—1027

@pageidx Support Functions

Index vector of specific observations.


Syntax: @pageidx(x)
x: vector, svector, string
Return: vector

Returns a vector containing the index values in the current workfile page of the observations
specified in x.
• If x is a vector, the elements of x should be date numbers.
• If x is a svector, the elements of x should be string representations of dates.
• If x is a string, it should contain a space delimited list of dates.

Any specified observations that are not in the current page will be ignored.

This function is only available in regular frequency, non-panel workfiles.

Examples
wfcreate(wf=qwf) q 2001 2024
vstring vdates = "2010q2 2010q3 2021q1 2023q4"
svector sdates = @wsplit(vdates)

creates a workfile containing quarterly data from 2001 to 2024, creates a string object con-
taining four specific dates, and creates the corresponding svector with those string values.

Then the commands


vector id1 = @pageidx("2010q2 2010q3 2021q1 2023q4")
vector id2 = @pageidx(vdates)
vector id3 = @pageidx(sdates)

all create four element vectors containing the values {38, 39, 81, 92}.
vector(4) ndates
for !i = 1 to 4
ndates(!i) = @dateval(sdates(!i))
next
vector id4 = @pageidx(ndates)

uses a vector with date numbers to return the same vector.

Cross-references
See “Dates,” on page 104.
1028—Function Reference: P

See also @pageinidx (p. 1028), @pagesmplidx (p. 1030), @dateval (p. 825), and
@wsplit (p. 1216).

@pageinidx Support Functions

Indicators for whether a observation in a workfile page is in an index.


Syntax: @pageinidx(x)
x: vector
Return: vector

Returns a vector containing (0,1) boolean values for whether each observation in the cur-
rent workfile page is specified in x, where x contains the indices of observations.

Examples
wfcreate(wf=qwf) q 2001 2024
vector id1 = @pageidx("2010q2 2010q3 2021q1 2023q4")
vector include = @pageinidx(id1)

creates a workfile containing quarter observations from 2001 to 2024, identifies the index
values for four specific dates and then obtains the vector INCLUDE which has the value of 1
for those four dates, and 0 otherwise.

One useful application of this indicator vector is setting the workfile sample. Since ID1 is the
same length as the current page, the commands
vector include = @pageinidx(id1)
mtos(include, keep)
smpl if keep=1

set the current workfile sample to include only the four observations specified above.

Cross-references
See also @pageidx (p. 1027), @pagesmplidx (p. 1030), and mtos (p. 522).

@pagelist Support Functions

All workfile page names.


Syntax: @pagelist
Return: string

Returns a string containing a space delimited list of names of all of the pages in the active
workfile.
@pagerange—1029

Examples
string allnames = @pagelist

saves the list of all of the pages in the workfile.


string temp = @pagelist
string pg = @word(@pagelist, 2)
pagedelete {pg}

deletes the second page in the workfile.

Cross-references
See also pageselect (p. 554), and pagesave (p. 548).

@pagename Support Functions

Name of active workfile page.


Syntax: @pagename
Return: string

Returns a string containing the name of the active page in the workfile.

Examples
string pgname = @pagename

saves the name of the active workfile page in the string variable PGNAME.

The commands
%name = @pagename
pagedelete {%name}

delete the current page.

Cross-references
See also @wfname (p. 1198) and @wfpath (p. 1198).

@pagerange Support Functions

Range specification in active workfile page.


Syntax: @pagerange
Return: string

Returns a string containing the range specification for the active page in the workfile.
1030—Function Reference: P

Examples
string smplstr = @pagesmpl

places the range string in the string variables SMPLSTR.

Cross-references
See also smpl (p. 592) and @pagesmpl (p. 1030).

@pagesmpl Support Functions

Sample specification in active workfile page.


Syntax: @pagesmpl
Return: string

Returns a string containing the current sample specification for the active page in the work-
file.

Examples
smpl 2010 2022 if inflation > 3.0
string smplstr = @pagesmpl

places the workfile string in the string variables SMPLSTR.

Cross-references
See also smpl (p. 592) and @pagerange (p. 1029)

@pagesmplidx Support Functions

Index vector of observations in the current sample.


Syntax: @pagesmplidx
Return: vector

Returns a vector containing the index values of the observations in the current sample in the
active workfile page.

Examples
wfcreate(wf=awf) a 2001 2024
smpl 2002 2003 2010 2011

creates a workfile containing annual observations from 2001 to 2024, then sets the sample to
contain observations from 2002–2003 and 2010–2011. There are 24 observations in this work-
file which may be identified by index values 1 to 24.
@pca—1031

vector ids = @pagesmplidx

creates a vector containing the values {2, 3, 10, 11} corresponding to the index values of the
sample observations.

Cross-references
See also smpl (p. 592), @pageidx (p. 1027), @pageinidx (p. 1028).

@pc Series Utility

One-period percentage change (in percent).


Syntax: @pc(x)
x: series
n: integer, series
Return: series

Returns one-period percentage change (in percent) in the series x:


xt – xt – 1
y t  100  ---------------------
-
xt – 1
This function is panel aware.

Examples
If x is a series of monthly profits, then
show @pc(x)

produces a linked series of monthly profit growth in percent.

Cross-references
See also @pca (p. 1031), @pch (p. 1033), @pcha (p. 1033), @pchy (p. 1034), and @pcy
(p. 1036).

@pca Series Utility

One-period percentage change, annualized (in percent).


Syntax: @pca(x)
x: series
n: integer, series
Return: series

Returns the n-th root of the total return of x over n periods, minus 1:
1032—Function Reference: P

 x t – x t – 1 n 
y t  100    1  ---------------------
- – 1
 xt – 1 
 

where n is the lag associated with the yearly frequency (e.g., n  4 for quarterly data,
n  12 for monthly data).
This function is panel aware.

Examples
If x is a series of monthly profits, then
show @pca(x)

produces a linked series of annualized profit growth in percent.

Cross-references
See also @pc (p. 1031), @pch (p. 1033), @pcha (p. 1033), @pchy (p. 1034), and @pcy
(p. 1036).

@pccagr Series Utility

Annualized growth rate (in percent).


Syntax: @pccagr(x, n)
x: series
n: integer
Return: series

Returns the n-th root of the total annual return of x over n periods, minus 1, multiplied by
100:
1
 --- 
xt  n
y t  100    ----------
- – 1
  xt – n  
 
This function is panel aware.

Examples
If x is a series of quarterly profits, then
show @pccagr(x, 1)

returns a linked series containing annualized profit growth rates in percent.


@pcha—1033

Cross-references
See also @cagr (p. 732).

@pch Series Utility

One-period percentage change (in decimal fraction).


Syntax: @pch(x)
x: series
n: integer, series
Return: series

Returns one-period percentage change (in decimal fraction) in the series x:


xt – xt – 1
y t  ---------------------
-
xt – 1
This function is panel aware.

Examples
If x is a series of monthly profits, then
show @pch(x)

produces a linked series of monthly profit growth in decimal fraction.

Cross-references
See also @pc (p. 1031), @pca (p. 1031), @pcha (p. 1033), @pchy (p. 1034), and @pcy
(p. 1036).

@pcha Series Utility

One-period percentage change, annualized (in decimal fraction).


Syntax: @pcha(x)
x: series
n: integer, series
Return: series

Returns one-period percentage change (in decimal fraction) in the series x:


x t – x t – 1 n
y t   1  ---------------------
- –1
 xt – 1 
1034—Function Reference: P

where n is the lag associated with the yearly frequency (e.g., n  4 for quarterly data,
n  12 for monthly data).
This function is panel aware.

Examples
If x is a series of monthly profits, then
show @pcha(x)

produces a linked series of annualized profit growth in decimal fraction.

Cross-references
See also @pc (p. 1031), @pca (p. 1031), @pch (p. 1033), @pchy (p. 1034), and @pcy (p. 1036).

@pchy Series Utility

One-year percentage change (in decimal fraction).


Syntax: @pchy(x)
x: series
n: integer, series
Return: series

Returns one-year percentage change (in decimal fraction) in the series x:


xt – xt – n
y t  ---------------------
-
xt – n

where n is the lag associated with the yearly frequency (e.g., n  4 for quarterly data,
n  12 for monthly data).
This function is panel aware.

Examples
If x is a series of monthly profits, then
show @pchy(x)

produces a linked series of one-year profit growth in decimal fraction.

Cross-references
See also @pc (p. 1031), @pca (p. 1031), @pch (p. 1033), @pcha (p. 1033), and @pcy (p. 1036).
@pctiles—1035

@pctiles Series Utility

Percentile values.

Determine the percentile associated with each value.


Syntax: @pctiles(x[, z, s])
x: series, vector, matrix
z: (optional) string literal
s: (optional) sample string or object when x is a series and assigning to a
series
Return: series

If r t is the ranking associated with observation t of T , the percentile is given by


r
y t  100  ----t
T
The z option controls tie-handling with rankings handled according to the setting:
• “i” (ignore), “f” (first), “l” (last), “a” (average - default), “r” randomize.

For series calculations, EViews will use the current or specified workfile sample.

Examples
Let x be a vector of length 4 with elements 1, 2, 3, 4. Then
= @pctiles(x)

returns a vector whose elements are 25, 50, 75, 100.


matrix y = @mnrnd(200, 4)
matrix pct1 = @pctiles(y, "a")
matrix pct2 = 100 * @ranks(y, "a") / @obs(y)

compute the percentiles of the randomly generated matrix Y directly using @pctiles and
indirectly using @ranks. Both PCT1 and PCT2 are 200  4 matrices where each element is
the percentile of the corresponding element of Y amongst all elements.

Cross-references
See also @quantile (p. 1057).
1036—Function Reference: P

@pcy Series Utility

One-year percentage change, (in percent).


Syntax: @pcy(x)
x: series
n: integer, series
Return: series

Returns one-year percentage change (in percent) in the series x:


xt – xt – n
y t  100  ---------------------
-
xt – n

where n is the lag associated with the yearly frequency (e.g., n  4 for quarterly data,
n  12 for monthly data).
This function is panel aware.

Examples
If x is a series of monthly profits, then
show @pcy(x)

produces a linked series of one-year profit growth in percent.

Cross-references
See also @pc (p. 1031), @pca (p. 1031), @pch (p. 1033), @pcha (p. 1033), and @pchy
(p. 1034).

@periodtodate Cumulative Statistics

Within-period cumulative sum (period-to-date).


Syntax: @periodtodate(x, y[, s])
x: series
y: series
s: (optional) sample string or object
Return: series

Cumulative sum of series x within each period, where each period is defined by a contigu-
ous block of identical values in series y, subject to limitations imposed by the optional sam-
ple or workfile sample.
@pi—1037

This function is panel aware.

Examples
If x is a series of monthly profits, then
show @periodtodate(x, @quarter)

returns a linked series of quarter-to-date monthly profits.

Cross-references
See also @ytd (p. 1223).

@permute Matrix Transformation

Permutation of matrix.
Syntax: @permute(m)
m: data object
Return: data object

Returns a data object whose rows are randomly drawn without replacement from rows of the
input m. The output has the same type and size as the input object.

To draw with replacement from rows of a data object, use @resample (p. 1071).

Examples
matrix xp = @permute(x)

yields the matrix XB whose rows were randomly sampled without replacement from the
matrix X.

Cross-references
See also @colsort (p. 759), @rowsort (p. 1091), and @sort (p. 1116).

See also @ranks (p. 1064) as well as @capplyranks (p. 733) and @rapplyranks (p. 1065).

See also @resample (p. 1071).

@pi Numeric Constants

Pi – ratio of a circle's circumference to its diameter ( p ).


Syntax: @pi
Return: number
1038—Function Reference: P

Examples
= @sin(@pi/2)

returns 1.

Cross-references
See also @log2pi (p. 949).

@pinverse Matrix Algebra

Moore-Penrose pseudo-inverse of matrix.


Syntax: @pinverse(m)
m: matrix, sym
Return: matrix, sym

Returns the Moore-Penrose pseudo-inverse of a matrix object or sym.

The pseudo-inverse has the property that both pre-multiplying and post-multiplying the
pseudo-inverse by the source matrix returns the source matrix, and that both pre-multiply-
ing and post-multiplying the source matrix by the pseudo-inverse will return the pseudo-
inverse.

For matrix X and pseudo-inverse X ,

XX X  X
– – –
X XX  X
Calling the function to produce the pseudo-inverse of a matrix returns a matrix, while the
pseudo-inverse of a sym returns a sym. Note that pseudo-inverting a sym is much faster
than inverting a matrix.

Examples
matrix m1 = @mnrnd(10, 10)
matrix m1p = @pinverse(m1)

computes the pseudo-inverse of a randomly generated matrix M1.


matrix m2p = @pinverse(@inner(m1))

computes the pseudo-inverse of the PSD inner product of M1.

The following validate the properties of the pseudo-inverse:


matrix diff1 = m1 * m1p * m1 - m1
matrix diff2 = m1p * m1 * m1p - m1p
@pmin—1039

as both DIFF1 and DIFF2 equal zero.

Cross-references
See also @inverse (p. 926) and @issingular (p. 931).

@pmax Series Utility

Pairwise maximum.
Syntax: @pmax(x, y)
x: series
y: series
Return: series

Returns the pairwise maximum of x and y (for more than two series, use @rmax (p. 1082)).
Missing values propagate.

Examples
Let x and y be series objects.
show @pmax(x,y)

returns a linked series of observation-wise maximums in x and y.

Cross-references
See also @pmin (p. 1039) and @rmax (p. 1082).

@pmin Series Utility

Pairwise minimum.
Syntax: @pmin(x, y)
x: series
y: series
Return: series

Returns the pairwise minimum of x and y (for more than two series, use @rmin (p. 1084)).
Missing values propagate.

Examples
Let x and y be series objects.
show @pmin(x,y)
1040—Function Reference: P

returns a linked series of observation-wise minimums in x and y.

Cross-references
See also @pmax (p. 1039) and @rmin (p. 1084).

@pmt Element Functions

Payment amount required for annuity to pay given present value.


Syntax: @pmt(r, n, pv[, v, bf])
r: number
n: integer
pv: number
v: (optional) number
bf: (optional) number
Return: number

Find the receipt amount x required to produce at least the present value pv from an n-period
annuity, with discount rate r, and optional receipt of a final lump sum v.

A non-zero value for the optional bf indicates that the receipts are made at the beginning of
periods (annuity due) instead of ends (ordinary annuity).
• The present value of by n-periods of ordinary annuity receipts and a final lump sum
is:
n
1  r – 1 v
PVO  x  ----------------------------------  --------------------
n n
1  r r 1  r
• The present value of n-periods of annuity due receipts and a final lump sum is:
n
 ---------------------------------
1  r – 1
-  1  r – 1 
n
 r  v
PVD  x   ----------------------------------------------------------------------------   --------------------
n n
 1  r  1  r
 
Then for a given PVO or PVD and annuity type, the function returns the smallest x required
for the present values to exceed the required value.

Examples
= @pmt(0.05, 10, 1000)

returns the value 129.5046, indicating that a 10-period annuity that pays $129.50 per period
has a present value of around $1000 assuming the discount rate of 5%.
@pow1pm1—1041

Cross-references
See also @fv (p. 889), @nper (p. 1013), @pv (p. 1044), and @rate (p. 1066).

@pow Element Functions

Power function.
Syntax: @pow(x, y)
x: number
y: number
Return: number
y
Returns the y power of x : z  x . If x  0 y must be an integer value.

Examples
= @pow(2,8)

returns 256.

Cross-references
See also @powm1 (p. 1042) and @pow1pm1 (p. 1041).

@pow1pm1 Element Functions

Power function of 1 plus argument, minus 1.


y
Returns z   1  x  – 1 .
Syntax: @pow1pm1(x, y)
x: number
y: number
Return: number

If x  0 , then y must be an integer value.


y
Provides higher precision calculation of  1  x  – 1 than direct evaluation using
@pow(1+x, y) - 1

for x near 1.

Examples
= @pow1pm1(0.07,10)

returns 0.96715....
1042—Function Reference: P

Cross-references
See also @pow (p. 1041) and @powm1 (p. 1042).

@powm1 Element Functions

Power function, minus 1.


y
Returns z  x – 1 .
Syntax: @powm1(x, y)
x: number
y: number
Return: number

If x  0 , then y must be an integer value.


y
Provides higher precision calculation of x – 1 than direct evaluation of
@pow(x, y) - 1
for x near 1.

Examples
= @powm1(1.07,10)

returns 0.96715....

Cross-references
See also @pow (p. 1041) and @pow1pm1 (p. 1041).

@prod Basic Statistics

Product.

Computes the product of the elements of x. Note that this function is prone to numeric over-
flow.
Syntax: @prod(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number
@psi—1043

T
y   xt
t1

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x is a series of length 5 whose elements are 1, 2, 3, 4, 5, then
= @prod(x)

returns 120 (or equivalently, 5!).

Cross-references
See also @inner (p. 922), @sum (p. 1135), and @sumsq (p. 1136).

@psi Element Functions

First derivative of the natural log of the gamma function.


Syntax: @psi(x)
x: number
Return: number
d log G  x  1 dG  x 
w  x   -----------------------  ----------- ---------------
dx G  x  dx
for x  0 .

Examples
= @psi(1)

returns -0.57721....

Cross-references
See also @digamma (p. 839), @gammalog (p. 894), and @trigamma (p. 1152).
1044—Function Reference: P

@pv Element Functions

Present value of annuity receipts and (optional) final lump sum receipt.
Syntax: @pv(r, n, x[, v, bf])
r: number
n: integer
x: number
v: (optional) number
bf: (optional) number
Return: number

Compute present value of receipt of an n-period annuity, with receipts x and discount rate r,
and optional receipt of a final lump sum v.

If n is not an integer, the integer floor n will be used.

A non-zero value for the optional bf indicates that the receipts are made at the beginning of
periods (annuity due) instead of ends (ordinary annuity).
• The present value of by n-periods of ordinary annuity receipts and a final lump sum
is:
n
1  r – 1 v
PVO  x  ----------------------------------  --------------------
n n
1  r r 1  r
• The present value of n-periods of annuity due receipts and a final lump sum is:
n
 ---------------------------------
1  r – 1
-  1  r – 1 
n
 r  v
PVD  x   ----------------------------------------------------------------------------   --------------------
n n
 1  r  1  r
 
Examples
= @pv(0.05, 15, 100)

returns the value 1037.966, indicating that a 15-period annuity that pays $100 per period has
a present value of $1037.97 assuming the discount rate of 5%.

Cross-references
See also @fv (p. 889), @nper (p. 1013), @pmt (p. 1040), and @rate (p. 1066).
@qbeta—1045

Function Reference: Q
@qbeta .................Beta distribution quantile (p. 1045).
@qbinom..............Binomial distribution quantile (p. 1046).
@qchisq ...............Chi-square distribution quantile (p. 1047).
@qexp ..................Exponential distribution quantile (p. 1047).
@qextreme ...........Extreme value (Type I-minimum) distribution quantile (p. 1048).
@qfdist .................F-distribution quantile (p. 1048).
@qform ................Quadratic form (p. 1049).
@qgamma ............Gamma distribution quantile (p. 1050).
@qged ..................Generalized error distribution quantile (p. 1050).
@qlaplace .............Laplace distribution quantile (p. 1051).
@qlogistic.............Logistic distribution quantile (p. 1052).
@qlognorm...........Log normal distribution quantile (p. 1052).
@qnegbin .............Negative binomial distribution quantile (p. 1053).
@qnorm ...............Standard normal distribution quantile (p. 1054).
@qpareto ..............Pareto distribution quantile (p. 1054).
@qpoisson ............Poisson distribution quantiles (p. 1055).
@qr ......................QR decomposition (p. 1055).
@qtdist .................Student’s t distribution quantile (p. 1056).
@quantile .............Empirical quantile (p. 1057).
@quantilesby ........Empirical quantiles of a series for each specified group (p. 1058).
@quarter ..............Quarter of the year of the observation (p. 1059).
@qunif .................Uniform distribution quantile (p. 1059).
@qweib ................Weibull distribution quantile (p. 1060).

@qbeta Element Functions

Beta distribution quantile.


Syntax: @qbeta(p, a, b)
p: number, 0  p  1
a: number, a  0
b: number, b  0
Return: number

Find the x satisfying


x
p  F  x a, b    f s a, b  ds
0
1046—Function Reference: Q

where
a–1 b–1
s 1 – s
f  s a, b   -------------------------------------- 0s1
B  a, b 
and 0 elsewhere, and B is the beta function
1
a–1 b–1 G  a G  b 
B  a, b   t 1 – t dt  ------------------------
Ga  b
0

Examples
= @qbeta(0.75, 1, 2)

returns 0.5.

Cross-references
See also @cbeta (p. 734), @dbeta (p. 828), and @rbeta (p. 1067).

@qbinom Element Functions

Binomial distribution quantile.


Syntax: @qbinom(v, n, p)
v: number, 0  v  1
n: integer, n  0
p: number, 0  p  1
Return: integer

Find value with cumulative probability exceeding v .

Returns smallest integer x  0 satisfying p  v where


x
n
  j  p  1 – p 
j n–j
p 
j0

is the cumulative probability function evaluated at x ,

Examples
= @qbinom(0.5, 5, 0.5)

returns 2.

Cross-references
See also @cbinom (p. 735), @dbinom (p. 828), and @rbinom (p. 1067).
@qexp—1047

@qchisq Element Functions

Chi-square distribution quantile.


Syntax: @qchisq(p, v)
p: number, 0  p  1
v: number, v  0
Return: number

Find the x satisfying


x
p  F  x, v    f  s, v  ds
0

where
1 v  2 – 1 –s  2
f  s, v   ------------------------------ s e
v2
2 Gv  2

Examples
= @qchisq(0.5, 100)

returns 99.33412....

Cross-references
See also @cchisq (p. 736), @chisq (p. 742), @dchisq (p. 830), and @rchisq (p. 1068).

@qexp Element Functions

Exponential distribution quantile.


Syntax: @qexp(p, m)
p: number, 0  p  1
m: number, m  0
Return: number

Return the x satisfying


–x  m
p  F  x, m   1 – e
so that
x  – m  log  1 – p 
1048—Function Reference: Q

Examples
= @qexp(0.5, 1)

returns 0.69314... (equal to log(2)).

Cross-references
See also @cexp (p. 738), @dexp (p. 837), and @rexp (p. 1072).

@qextreme Element Functions

Extreme value (Type I-minimum) distribution quantile.


Syntax: @qextreme(p)
p: number, 0  p  1
Return: number

Return the x satisfying


x
p  F  x   1 – exp  – e 
so that
x  log  – log  1 – p  
Examples
= @qextreme(0.5)

returns -0.36651....

Cross-references
See also @cextreme (p. 739), @dextreme (p. 837), and @rextreme (p. 1072).

@qfdist Element Functions

F-distribution quantile.
Syntax: @qfdist(p, v 1 , v 2 )
p: number
v1 : number, v 1  0
v2 : number, v 2  0
Return: number

For 0  p  1 , find the x satisfying


@qform—1049

x
p  F  x v 1, v 2    fs v 1, v 2  ds
0

where,
v 2 v 2
v 11 v 22 v – 2  2 – v  v   2
f  x v 1, v 2   -------------------------------------
-x 1  v2  v1 x  1 2
B  v 1  2, v 2  2 

for x  0 and 0 otherwise, and B is the beta function


1 a–1 b–1 G  a G  b 
B  a, b   0 t 1 – t dt  ------------------------
Ga  b
Examples
= @qfdist(0.5, 2, 2)

returns 1.

Cross-references
See also @cfdist (p. 739), @fdist (p. 882), @dfdist (p. 838), and @rfdist (p. 1073).

@qform Matrix Algebra

Quadratic form.
Syntax: @qform(s, o)
s: sym
o: vector, matrix, sym
Return: number, sym

Returns the quadratic form of a symmetric matrix s, with a vector or matrix object o.
y  oso
• if o is a vector, the function returns a scalar
• If o is a matrix, the function returns a sym

Examples
sym s1 = @inner(@mnrnd(20, 4))
vector v1 = @mrnd(4)
scalar q1 = @qform(@inverse(s1), v1)

generates a symmetric matrix S1, then computes the quadratic form using the inverse of S1,
and the randomly generated vector V1.
matrix m1 = @mrnd(4, 5)
1050—Function Reference: Q

sym q2 = @qform(@inverse(s1), m1)

computes the matrix form of the quadratic form, returning a sym.

Cross-references
See also @inner (p. 922) and @outer (p. 1021).

@qgamma Element Functions

Gamma distribution quantile.


Syntax: @qgamma(p, b, r)
p: number, 0  p  1
b: number, b  0
r: number, r  0
Return: number

Return the x satisfying


x
p  F  x b, r   0 f  s b, r  ds

where
–r r – 1 –x  b
b x e
f  s, b, r   --------------------------------
Gr
for x  0 and 0 elsewhere.

Examples
= @qgamma(0.5, 4, 1)

returns 2.77258....

Cross-references
See also @cgamma (p. 741), @dgamma (p. 838), and @rgamma (p. 1074).

@qged Element Functions

Generalized error distribution quantile.


Syntax: @qchisq(p, r)
p: number, 0  p  1
r: number, r  0
Return: number
@qlaplace—1051

Find the x satisfying


x
p  Fx r   fs r  ds
0

where
3 12  G  3---   
r2
r G  --- 
 r  r   r  
f  s, r   ------------------------ exp  – s  -------------- 
32
2 G  ---
1   G  1---   
 r    r  

Examples
= @qged(0.75, 2)

returns 0.67448....

Cross-references
See also @cged (p. 742), @dged (p. 839), and @rged (p. 1074).

@qlaplace Element Functions

Laplace distribution quantile.


Syntax: @qlaplace(p)
p: number
Return: number

Return the x satisfying


x
p  Fx m   f s  ds
–

where
1 –s
f  s   --- e
2

Examples
= @qlaplace(0.25)

returns -0.69314....

Cross-references
See also @claplace (p. 747), @dlaplace (p. 841), and @rlaplace (p. 1080).
1052—Function Reference: Q

@qlogistic Element Functions

Logistic distribution quantile.


Syntax: @qlogistic(p)
p: number, 0  p  1
Return: number

Return the x satisfying


1
p  F  x   ----------------------
–x
1  e 
so that
1–p
x  – log  ------------
 p 

Examples
= @qlogistic(0.5)

returns 0.

Cross-references
See also @clogistic (p. 748), @dlogistic (p. 843), and @rlogistic (p. 1081).

@qlognorm Element Functions

Log normal distribution quantile.


Syntax: @qchisq(p, m, s)
p: number, 0  p  1
m: number, m  0
s: number, s  0
Return: number

Find the x satisfying


x
p  F  x m, s    fv m, s  dv
0

where
@qnegbin—1053

1 2 2
f  v, m, s   ------------------- exp  –  log x – m    2s  
2
x 2ps
Examples
= @qlognorm(0.5, 0, 2)

returns 1.

Cross-references
See also @clognorm (p. 749), @dlognorm (p. 843), and @rlognorm (p. 1082).

@qnegbin Element Functions

Negative binomial distribution quantile.


Syntax: @qnegbin(v, n, p)
v: number, 0  p  1
n: number, n  0
p: number, 0  p  1
Return: integer

Find value with cumulative probability exceeding p .

Returns smallest integer x  0 satisfying p  v where


x Gj  n j n
p   --------------------------------
-p  1 – p 
G  j  1 G  n 
j0

is the cumulative probability function evaluated at x ,

Examples
= @qnegbin(0.5, 10, 0.5)

returns 9.

Cross-references
See also @cnegbin (p. 753), @dnegbin (p. 845), and @rnegbin (p. 1087).
1054—Function Reference: Q

@qnorm Element Functions

Standard normal distribution quantile.


Syntax: @qnorm(p)
p: number
Return: number

Return the x satisfying


x
p  Fx   f  s  ds
–

where
–1  2 2
f  s    2p  exp  – s  2 

Examples
= @qnorm(0.95)

returns 1.64485....

Cross-references
See also @cnorm (p. 753), @logcnorm (p. 950), @dnorm (p. 845), and @rnorm (p. 1087).

@qpareto Element Functions

Pareto distribution quantile.


Syntax: @qpareto(p, m, a)
p: number, 0  p  1
m: number, m  0
a: number, a  0
Return: number

Return the x satisfying


a
p  F  x m, a   1 – exp  –  x  m  
Examples
= @qpareto(0.75, 1, 2)

returns 2.
@qr—1055

Cross-references
See also @cpareto (p. 769), @dpareto (p. 846), and @rpareto (p. 1092).

@qpoisson Element Functions

Poisson distribution quantiles.


Syntax: @qpoisson(p, m)
p: number, 0  p  1
m: number, m  0
Return: integer

Find value with cumulative probability exceeding p .

Returns smallest integer x  0 satisfying p  v where


x j –m
p  me  j!
j0

is the cumulative probability function evaluated at x ,

Examples
= @qpoisson(0.5, 10)

returns 10.

Cross-references
See also @cpoisson (p. 770), @dpoisson (p. 846), and @rpoisson (p. 1092).

@qr Matrix Algebra

QR decomposition.
Syntax: @qr(M, R[, P])
M: matrix
R: matrix
P: (optional) matrix
Return: matrix Q

Decomposes an m  n matrix M into an m  m orthogonal matrix Q and an m  n


upper triangular matrix R such that M  QR , where m  n .

If permutation matrix P is provided, the decomposition produces Q and R such that


MP  QR .
1056—Function Reference: Q

Examples
matrix m1 = @mnrnd(7, 5)
matrix r
matrix q = @qr(m1, r)

generates a random matrix M1, then decomposes it into the orthogonal matrix Q, and the
upper triangular matrix R.

The following illustrate the properties of the decomposition:


sym i1 = @inner(q)
matrix m2 = q * r

where I1 is the identity matrix, and M2 is equal to M1.

Cross-references
See also @cholesky (p. 743), @lu (p. 954), @svd (p. 1137), and @svdfull (p. 1139).

@qtdist Element Functions

Student’s t distribution quantile.


Syntax: @qtdist(p, v)
p: number, 0  p  1
v: number, v  0
Return: number

Return the x satisfying


x
p  Fx v  – f  s v  ds

where
v1
G  ------------ v  1
–--------------------
 2  s
2 2
f  s v   ---------------------------  1   ----  
1---   v 
v
 vp  G  ---
2
 2

Examples
= @qtdist(0.025, 1)

returns -12.70620....

Cross-references
See also @ctdist (p. 775), @tdist (p. 1144), @dtdist (p. 847), and @rtdist (p. 1099).
@quantile—1057

@quantile Basic Statistics

Empirical quantile.

Compute the quantile value where approximately 100*q percent of the data is less than or
equal to the value,
Syntax: @quantile(x, q[, m, s])
x: series, vector, matrix
q: number, series, vector, matrix
m: (optional) string
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number
• The quantile value q must satisfy 0  q  1 .
• m is an optional string controlling the method of calculating the empirical distribution
function: “b” (Blom), “r” (Rankit-Cleveland), “o” (Ordinary), “t” (Tukey), “v” (van
der Waerden), “g” (Gumbel). The default value is “r”.

Rankit-Cleveland 1
r – ---  T
(default)  2
Ordinary rT
Van der Waerden r  T  1
Blom
 r – 3---   T  1---
 8  4
Tukey 1  1
r – ---  T  ---
 3  3
Gumbel r – 1  T – 1

To compute the q -quantile, first find r , the smallest rank such that,
q  F  x r  

where the order statistics  x  1 , x  2 , , x  T   represent data for the T observations


ordered from low to high, and F is the assumed empirical distribution function. For pur-
poses of computing F , tied ranks are assumed to take the last tied value.

Then the quantile is computed as


1058—Function Reference: Q

 x 1  if F  x  1    q

y    1 – d x  r – k   dx  r  if F  x  r – k    q  F  x  r  

 NA if F  x  t    q

where the interpolating constant is


q – F  x r – k  
d  -----------------------------------------------
-
F  x r   – F  x r – k  

for k  0 the smallest integer where F  x  r – k    q . In the leading case where there are no
tied x  r  values, k  1 .

For series calculations, EViews will use the current or specified workfile sample.

Examples
= @quantile(x, 0.5)

returns the median of the series x.


= @quantile(x, 0.1)

returns the first decile (10th percentile) of the series x.

Cross-references
See also @pctiles (p. 1035).

@quantilesby By-Group Statistics

Empirical quantiles of a series for each specified group.


Syntax: @quantilesby(x, y[y1, y2, ... yn], q, [s])
x: series
y: series, alpha
q number
s: (optional) sample string or object
Return: series

Returns the q-th quantile of x for each group defined by distinct values of y. The quantiles will
be computed using the Rankit-Cleveland definition (see @quantile (p. 1057)).

EViews will use the current or specified workfile sample.

Examples
show @quantilesby(x, g1, g2, 0.25)
@qunif—1059

produces a linked series of the by-group 25th percentiles of the series x, where members of
the same group have identical values for both g1 and g2.

Cross-references
See also @mediansby (p. 973).

@quarter Workfile Functions

Quarter of the year of the observation.


Syntax: @quarter
Return: series

Returns the quarter of the year (1–4) associated with each observation in the workfile.
• If the workfile is of lower than quarterly frequency, all observations will be set to 1.
• If the workfile is undated, observations will be set to -1.

Examples
series dt = @quarter
saves the quarter into the series DT.
The command
smpl if @quarter = 4
sets the sample to only include fourth quarter observations.

Cross-references
See also @day (p. 826), @hour (p. 910), @hourf (p. 910), @minute (p. 978), @month
(p. 983), @seas (p. 1109), @second (p. 1109), @weekday (p. 1192), and @year (p. 1223).

@qunif Element Functions

Uniform distribution quantile.


Syntax: @qunif(p, a, b)
p: number, 0  p  1
a: number
b: number, b  a
Return: number

Return the x satisfying


1060—Function Reference: Q

x – a
p  F  x a, b   -----------------
b–a
so that
x  a  pb – a
Examples
= @qunif(0.4, 1, 6)

returns 3.

Cross-references
See also @cunif (p. 806), @dunif (p. 849), and @runif (p. 1100).

@qweib Element Functions

Weibull distribution quantile.


Syntax: @qweib(p, m, a)
p: number, 0  p  1
m: number, m  0
a: number, a  0
Return: number

Return the x satisfying


a
p  F  x m, a   1 – exp  –  x  m  
Examples
= @qweib(0.5, 1, 1)

returns 0.69314... (the natural log of 2).

Cross-references
See also @cweib (p. 808), @dweib (p. 855), and @rweib (p. 1104).
Function Reference: R—1061

Function Reference: R
@range .................Vector of sequential integers (p. 1063).
@rank ..................Rank of a matrix (p. 1063).
@ranks .................Ranking of values (p. 1064).
@rapplyranks .......Reorder the columns of a matrix using a vector of ranks (p. 1065).
@rate....................Discount rate required for annuity to yield given present value
(p. 1066).
@rbeta..................Beta distribution random draw (p. 1067).
@rbinom ..............Binomial distribution random draw (p. 1067).
@rchisq ................Chi-square distribution random draw (p. 1068).
@recode ...............Recode value by condition (p. 1068).
@regress...............Perform an OLS regression on the first column of a matrix versus
the remaining columns (p. 1069).
@replace...............Replace substring in string (p. 1070).
@resample............Randomly draw from the rows of the matrix (p. 1071).
@rexp...................Exponential distribution random draw (p. 1072).
@rextreme ............Extreme value (Type I-minimum) distribution random draw
(p. 1072).
@rfdist .................F-distribution random draw (p. 1073).
@rfirst ..................First non-missing value in rows of group object (p. 1073).
@rgamma .............Gamma distribution random draw (p. 1074).
@rged...................Generalized error distribution random draw (p. 1074).
@rifirst .................Indices of first non-missing value in rows of group object (p. 1075).
@right ..................Right substring of string (p. 1075).
@rilast..................Indices of last non-missing value in rows of group object (p. 1076).
@rimax ................Indices of row maximums of group object (p. 1077).
@rimin .................Indices of row minimums of group object (p. 1077).
@rinstr .................Find substring position in string (p. 1078).
@riwish................Inverse Wishart random draws (p. 1079).
@rlaplace .............Laplace distribution random draw (p. 1080).
@rlast...................Last non-missing values in rows of group object (p. 1081).
@rlogistic .............Logistic distribution random draw (p. 1081).
@rlognorm ...........Log normal distribution random draw (p. 1082).
@rmax .................Row maximums of group object (p. 1082).
@rmean................Row means of group object (p. 1083).
@rmedian.............Row medians of group object (p. 1083).
@rmin ..................Row minimums of group object (p. 1084).
1062—Function Reference: R

@rmse ................. Root of the mean of square error (difference) between series
(p. 1084).
@rmvnorm .......... Multivariate normal random draws (p. 1085).
@rnas .................. Number of missing observations in row of group object (p. 1086).
@rnegbin ............. Negative binomial distribution random draw (p. 1087).
@rnorm ............... Standard normal distribution random draw (p. 1087).
@robs .................. Number of non-missing observations in row of group object
(p. 1088).
@round................ Nearest integer, or value at given precision (p. 1088).
@rowextract......... Extract rowvector from matrix object (p. 1089).
@rowranks .......... Matrix where each row contains ranks of the column values
(p. 1090).
@rows ................. Number of rows (p. 1090).
@rowsort ............. Matrix where each row contains sorted columns (p. 1091).
@rpareto .............. Pareto distribution random draw (p. 1092).
@rpoisson ............ Poisson distribution random draw (p. 1092).
@rprod ................ Row products in group object (p. 1093).
@rquantile ........... Row quantiles in group object (p. 1093).
@rstdev ............... Row sample (d.f. corrected) standard deviations of group object
(p. 1094).
@rstdevp.............. Row population (non d.f. corrected) standard deviations of group
object (p. 1095).
@rstdevs .............. Row sample (d.f. corrected) standard deviations of group object
(p. 1096).
@rsum ................. Row sums of group object (p. 1096).
@rsumsq.............. Row sums of squares of group object (p. 1097).
@rsweep .............. Reverse sweep operator (p. 1097).
@rtdist................. Student’s t distribution random draw (p. 1099).
@rtrim ................. Trim right whitespace of string (p. 1100).
@runif ................. Uniform distribution random draw (p. 1100).
@runpath............. Location of the program currently being executed (p. 1101).
@rvalcount .......... Number of matching values in rows of group object (p. 1101).
@rvar .................. Row population (non d.f. corrected) variances of group object
(p. 1102).
@rvarp................. Row population (non d.f. corrected) variances of group object
(p. 1102).
@rvars ................. Row sample (d.f. corrected) standard deviations of group object
(p. 1103).
@rweib ................ Weibull distribution random draw (p. 1104).
@rank—1063

@rwish.................Wishart random draw (p. 1104).

@range Matrix Utility

Vector of sequential integers.


Syntax: @range(n1, n2)
n1: integer
n2: integer
Return: vector

Returns a vector holding the sequential integers staring at n1 and ending at n2.

Examples
vector r1 = @range(1, 10)

create a vector containing sequential integers from 1 to 10.


vector r2 = @range(10, -3)

creates a vector containing integers starting at 10 and continuing to -3.


matrix m1a = m1.@sub(@range(3, m1.@rows), @range(2, m1.@cols))

extracts a submatrix from M1 starting at row 3 and column 2 and continuing to the end of
the matrix.
matrix m1b = m1.@sub(@range(3, 7), @range(2, 4))

extracts a submatrix from M1 from row 3 to 7 and column 2 to 4.

Cross-references
See also @grid (p. 897) and @seq (p. 1110).

@rank Matrix Algebra

Rank of the matrix.


Syntax: @rank(m[, n])
m: matrix, sym, vector, series
n: (optional) number
Return: integer

The rank of m is calculated by counting the number of singular values of the matrix which
are smaller in absolute value than the tolerance, n.
1064—Function Reference: R

If n is not provided, EViews uses the value given by the largest dimension of the matrix mul-
tiplied by the norm of the matrix multiplied by machine epsilon (the smallest representable
number).

Examples
= @rank(m1)

returns the rank of the matrix M1. If M1 is a matrix of zeros, its rank is 0. If M1 is a matrix
of a non-zero constant, its rank is 1.

Cross-references
See also @det (p. 835) and @svd (p. 1137).

To obtain a ranking of the elements in a matrix, see @ranks (p. 1064) as well as @colranks
(p. 758) and @rowranks (p. 1090).

@ranks Series Utility

Ranking of values.

Determine the ranking associated with each value.


Syntax: @ranks(x[, y, z, s])
x: series, vector, matrix
y: (optional) string literal
z: (optional) string literal
s: (optional) sample string or object when x is a series
Return: series, vector, matrix object

The optional arguments control the behavior of the ranking procedure

The y option controls the direction of the ranking:


• “a” (ascending - default) or “d” (descending)

The z option controls tie-handling with rankings handled according to the setting:
• “i” (ignore), “f” (first), “l” (last), “a” (average - default), “r” randomize.

For series calculations, EViews will use the current or specified workfile sample.

Examples
vector y = @ranks(x, "a", "i")

returns the unique integer ascending ranking for the data in vector x, ignoring ties.
@rapplyranks—1065

Cross-references
See also @pctiles (p. 1035).

@rapplyranks Matrix Utility

Reorder the columns of a matrix using a vector of ranks.


Syntax: @rapplyranks(m, v[, n])
m: matrix, vector
v: vector
n: (optional) integer
Return: matrix, vector

Apply (a row of) column ranks in the vector v to reorder the columns of a matrix m using
the ranks.
• v should contain unique integers from 1 to the number of columns of m.
• If the optional argument n is specified, only the elements in row n will be reordered.

Examples
vector v1 = @ranks(m1.@row(3), "a", "i")
matrix m2 = @rapplyranks(m1, v1)

reorders the columns of the matrix M1 using the ranks in V1. Note that you may use the
@ranks function to obtain the ranks of a vector but must obtain unique integer ranking for
data with ties through use of the “i” or “r” option in @ranks.
matrix m3 = @rapplyranks(m1, v1, 3)

reorders only the elements in row 3 of M1.

Cross-references
See also @sort (p. 1116), @colsort (p. 759), and @rowsort (p. 1091).

See also @ranks (p. 1064), @colranks (p. 758), and @rowranks (p. 1090).

See also @capplyranks (p. 733).


1066—Function Reference: R

@rate Element Functions

Discount rate required for annuity to yield given present value.


Syntax: @rate(n, x, pv[, v, bf])
n: integer
x: number
pv: number
v: (optional) number
bf: (optional) number
Return: number

Find the largest discount rate r producing at least the present value pv from an n-period
annuity, with receipts x, and optional receipt of a final lump sum v.

If n is not an integer, the integer floor n will be used.

A non-zero value for the optional bf indicates that the receipts are made at the beginning of
periods (annuity due) instead of ends (ordinary annuity).
• The present value of by n-periods of ordinary annuity receipts and a final lump sum
is:
n
1  r – 1 v
PVO  x  ----------------------------------  --------------------
n n
1  r r 1  r
• The present value of n-periods of annuity due receipts and a final lump sum is:
n
 ---------------------------------
1  r – 1
-  1  r – 1 
n
 r  v
PVD  x   ----------------------------------------------------------------------------   --------------------
n n
 1  r  1  r
 
Then for a given PVO or PVD and annuity type, the function returns the largest discount rate
r where the present values still exceed the required value.

Examples
= @rate(15, 100, 1000)

returns the value 0.055565, indicating that a 15-year annuity that pays $100 per period has a
present value of $1000 if the discount rate is set to 0.055565.

Cross-references
See also @fv (p. 889), @nper (p. 1013), @pmt (p. 1040), and @pv (p. 1044).
@rbinom—1067

@rbeta Element Functions

Beta distribution random draw.


Syntax: @rbeta(x, a, b)
x: number
a: number, a  0
b: number, b  0
Return: number

Draw a random value from the beta distribution with density function,
a–1 b–1
x 1 – x
f  x, a, b   -------------------------------------- 0x1
B  a, b 
and 0 elsewhere, where B is the beta function
1
a–1 b–1 G  a G  b 
B  a, b   t 1 – t dt  ------------------------
Ga  b
0

Examples
= @rbeta(1, 2)

returns a random draw from the Beta(1, 2) distribution.

Cross-references
See also @cbeta (p. 734), @dbeta (p. 828), and @qbeta (p. 1045).

@rbinom Element Functions

Binomial distribution random draw.


Syntax: @rbinom(n, p)
n: integer, n  0
p: number, 0  p  1
Return: integer

Draw a random integer value from the binomial distribution with probability function,

 n x
p  x, n, p      p  1 – p 
n–x
x  0, 1, , n
x 

and 0 elsewhere.
1068—Function Reference: R

Examples
= @rbinom(5, 0.5)

returns a random draw from the Binom(5, 0.5) distribution.

Cross-references
See also @cbinom (p. 735), @dbinom (p. 828), and @qbinom (p. 1046).

@rchisq Element Functions

Chi-square distribution random draw.


Syntax: @rchisq(v)
v: number, v  0
Return: number

Draw a random value from the chi-square distribution with density function,
1 v  2 – 1 –x  2
f  x, v   ------------------------------ x e
v2
2 Gv  2

Examples
= @rchisq(10)

returns a random draw from the chi-square distribution with 10 degrees of freedom.

Cross-references
See also @cchisq (p. 736), @chisq (p. 742), @dchisq (p. 830), and @qchisq (p. 1047).

@recode Element Functions

Recode value by condition.

Returns x if condition s is non-zero (true); otherwise returns y .


Syntax: @recode(s, x, y)
s: number
x: number or string
y: number or string
Return: number or string

Returns x if s is non-zero (true); otherwise returns y .


@regress—1069

Typically s is specified using an expression with a boolean operator or function returning


(0, 1) values (e.g., “z > 3”or “z > w”), but any argument providing (0, non-zero) values is
sufficient.

Examples
= @recode(x<0, 1, 0)

returns 1 if x is negative, 0 otherwise.

Cross-references
See also @iif (p. 915) and @nan (p. 1009).

@regress Basic Statistics

Perform an OLS regression on the first column of a matrix versus the remaining columns.
Syntax: @regress(m[, v])
m: matrix
v: (optional) vector
Return: matrix

Returns the results of an OLS regression on the first column of matrix m versus the remain-
ing columns of m.

The returned matrix contains four columns of information: (1) regression coefficient values,
(2) standard errors, (3) t-test statistics, and (4) associated p-values.

If an optional vector v is supplied, the regression residuals are stored in v.

Examples
matrix results = @regress(yxmat)

estimates a regression on the data in the columns of the matrix YXMAT and saves the coeffi-
cient, standard error, t-statistic and p-value results in columns of RESULTS

Next for comparison purposes we run a regression on random data using the equation
object, collect results in a matrix, and make a series containing the residuals.

First, create a workfile with random data, create a group with the dependent variable and
regressors, and set the workfile sample.
workfile q 2000 2022
series y = nrnd
series x1 = nrnd
series x2 = nrnd
group yx y 1 x1 x2
1070—Function Reference: R

smpl 2002 2022


equation eq1.ls y c x1 x2
matrix eq_results = @hcat(eq1.@coefs, eq1.@stderrs, eq1.@tstats,
eq1.@pvals)
eq1.makeresids eq_resids

The function offers a quick way of obtaining equivalent results,


vector fn_resids
matrix fn_results = @regress(@convert(yx), fn_resids)

Cross-references
See also @solvesystem (p. 1115) as well as @intercept (p. 925) and @trendcoef
(p. 1151).

@replace Element Functions | String Functions

Replace substring in string.


Syntax: @replace(str1, str2, str3[, n])
str1: string, alpha, svector
str2: string, alpha, svector
str3: string, alpha, svector
n: (optional) integer, series, vector
Return: string, alpha, svector

Returns the base string str1, with the str3 substituted for the target string str2. By default, all
occurrences of str2 will be replaced, but you may provide an optional integer n to specify
the maximum number of occurrences to be replaced.

Examples
@replace("Do you think that you can do it?", "you", "I")

returns the string “Do I think that I can do it?”, while


@replace("Do you think that you can do it?", "you", "I", 1)

only replaces the first instance of “you” with “I” so that it returns “Do I think that you can
do it?”.

If ALPHA1 is an alpha series,


alpha a1 = @replace(alpha1, "abc", "def")

replaces all instances of “abc” with “def” in ALPHA1 for all observations in the workfile
sample.
@resample—1071

If AVEC1 and AVEC2 are string vectors,


svector s1 = @replace(avec1, avec2, "abc")

replaces all instances of the strings in AVEC2 with “abc” for each element of AVEC1.

Cross-references
See also @insert (p. 923), @mid (p. 974), @wreplace (p. 1211), and @wnotin (p. 1207).

@resample Series Utility

Randomly draw from the rows of the data object.


Syntax: @resample(m[, n1, n2, v])
m: data object
n1: (optional) integer
n2: (optional) positive integer
v: (optional) vector
Output: data object

Returns a data object whose rows are randomly drawn with replacement from rows of the
input matrix or vector.

By default, the output matrix will be the same size as the source m.
• n1 represents the number of “extra” rows to be drawn from the matrix. If the input
matrix has r rows and c columns, the output matrix will have r  n1 rows and c col-
umns. By default, n1=0 .
• n2 represents the block size for the resample procedure. If you specify n2  1 , then
blocks of consecutive rows of length n2 will be drawn with replacement from the
first r – n2  1 rows of the input matrix.
• You may provide a name for the vector v to be used for weighted resampling. The
weighting vector must have length r and all elements must be non-missing and non-
negative. If you provide a weighting vector, each row of the input matrix will be
drawn with probability proportional to the weights in the corresponding row of the
weighting vector. (The weights need not sum to 1. EViews will automatically normal-
ize the weights).

To draw without replacement from rows of a matrix, use @permute (p. 1037).

Examples
matrix xb = @resample(x)
1072—Function Reference: R

yields the matrix XB whose rows were randomly sampled with replacement from the matrix
X.

Cross-references
See also @permute (p. 1037).

@rexp Element Functions

Exponential distribution random draw.


Syntax: @rexp(m)
m: number, m  0
Return: number

Draw a random value from the exponential distribution with probability density function,

 0 x0

f  x, m    1 – x  m
 ----e x0
m

Examples
= @rexp(1)

returns a random draw from the exponential distribution with mean 1.

Cross-references
See also @cexp (p. 738), @dexp (p. 837), and @qexp (p. 1047).

@rextreme Element Functions

Extreme value (Type I-minimum) distribution random draw.


Syntax: @extreme
Return: number

Draw a random value from the extreme value distribution with probability density function,
x
f  x   exp  x – e 

Examples
= @rextreme

returns a random draw from the extreme value distribution.


@rfirst—1073

Cross-references
See also @cextreme (p. 739), @dextreme (p. 837), and @qextreme (p. 1048).

@rfdist Element Functions

F-distribution random draw.


Syntax: @rfdist( v 1 , v 2 )
v1 : number, v 1  0
v2 : number, v 2  0
Return: number

Draw a random value from the F-distribution with density function,


v 2 v 2
v 11 v 22 v – 2  2 – v  v   2
f  x v 1, v 2   -------------------------------------
-x 1  v2  v1 x  1 2
B  v 1  2, v 2  2 

for x  0 and 0 otherwise, where B is the beta function,


1 a–1 b–1 G  a G  b 
B  a, b   0 t 1 – t dt  ------------------------
Ga  b
Examples
= @rfdist(2, 2)

returns a random draw from the F-distribution with numerator and denominator degrees of
freedom 2.

Cross-references
See also @cfdist (p. 739), @fdist (p. 882), @dfdist (p. 838), and @qfdist (p. 1048).

@rfirst Element Functions

First non-missing value in rows of group.

Value of the first non-missing value in each row of the group.


Syntax: @rfirst(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


find the first non-missing value in the row.
1074—Function Reference: R

Examples
show @rfirst(g

returns a linked series of the first non-missing observations in the rows of group g.

Cross-references
See also @rlast (p. 1081), @rifirst (p. 1075), and @rilast (p. 1076).

@rgamma Element Functions

Gamma distribution random draw.


Syntax: @rgamma(b, r)
b: number, b  0
r: number, r  0
Return: number

Draw a random value from the gamma distribution with the probability density function,
–r r – 1 –x  b
b x e
f  x b, r   --------------------------------
Gr
for x  0 , and 0 elsewhere.

Examples
= @rgamma(4, 1)

returns a random draw from the Gamma(4, 1) distribution.

Cross-references
See also @cgamma (p. 741), @dgamma (p. 838), and @qgamma (p. 1050).

@rged Element Functions

Generalized error distribution random draw.


Syntax: @rged(r)
r: number, r  0
Return: number

Draw a random value from the generalized error distribution with density function,
@right—1075

3 12  G  3---   
r2
r G  ---  
r   r   r   
f  x r   -------------------------- exp  – x  -------------- 
1 32   G  1---   
2 G  ---     r  
r 

Examples
= @rged(2)

returns a random draw from the Generalized error distribution.

Cross-references
See also @cged (p. 742), @dged (p. 839), and @qged (p. 1050).

@rifirst By-Row Statistics

Indices of first non-missing value in rows of group.

Column indices of first non-missing value in each row of the group.


Syntax: @rifirst(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


identify the column containing the first non-missing value in the row.

Examples
show @rifirst(g

returns a linked series of the indices corresponding to the first non-missing observations in
the rows of group g.

Cross-references
See also @rfirst (p. 1073), @rlast (p. 1081), and @rilast (p. 1076).

@right Element Functions | String Functions

Right substring of string.


Syntax: @right(str, n)
str: string, alpha, svector
n: integer, series, vector
Return: string, alpha, svector
1076—Function Reference: R

Returns a string containing n characters from the right end of str. If the source is shorter
than n, the entire string is returned.

Examples
The commands
string orig = "I doubt it"
string sc1 = @right("I doubt it", 8)
string sc2 = @left(orig, 8)

return the string objects SC1 and SC2 containing the string “doubt it”.

If ALPHA1 is an alpha series,


alpha strleft = @right(alpha1, 7)

returns the right-most 7 characters from the string values of ALPHA1 for each observation in
the workfile sample.

If SVEC1 is an string vector,


svector strleft = @right(svec1, 12)

returns an svector containing 12 characters from the right end of each element of SVEC1.

Cross-references
See also @wright (p. 1214),@left (p. 942), @wleft (p. 1203), @mid (p. 974), and @wmid
(p. 1206).

@rilast By-Row Statistics

Indices of last non-missing value in rows of group.

Column indices of last non-missing value in each row of the group.


Syntax: @rilast(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


identify the column containing the last non-missing value in the row.

Examples
show @rilast(g

returns a linked series of the indices corresponding to the last non-missing observations in
the rows of group g.
@rimin—1077

Cross-references
See also @rfirst (p. 1073), @rlast (p. 1081), and @rifirst (p. 1075).

@rimax By-Row Statistics

Indices of row maximums of group.

Column indices of maximum values across series in each row of the group.
Syntax: @rimax(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


identify the column containing the maximum value across the data for the row.

Examples
show @rimax(g

returns a linked series of the indices corresponding to the maximums in the rows of group g.

Cross-references
See also @rmax (p. 1082), @rmin (p. 1084), and @rimin (p. 1077).

@rimin By-Row Statistics

Indices of row minimums of group.

Column indices of minimum values across series in each row of the group.
Syntax: @rimin(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


identify the column containing the minimum value across the data for the row.

Examples
show @rimin(g

returns a linked series of the indices corresponding to the minimums in the rows of group g.

Cross-references
See also @rmax (p. 1082), @rmin (p. 1084), and @rimax (p. 1077).
1078—Function Reference: R

@rinstr Element Functions | String Functions

Find substring position in string, search in reverse.


Syntax: @rinstr(str1, str2[, n])
str1: string, alpha
str2: string, alpha
n: (optional) integer, series
Return: integer, series

Starting at the end of the string and searching in reverse, finds the starting position of the
target string str2 in the string str1. By default, the function returns the location of the last
(first from the end) instance of str2 in str1, but you may provide the optional integer n to
change the occurrence.

If the target string is not found, @rinstr will return a 0.

Examples
string sval = "1.2341534"
@rinstr("1.2341534", "34")
@instr(sval, "34")

return the value 4, since the substring “34” appears a second time (from the end of the
string) beginning in the fourth character of the base string.

If ALPHA1 is an alpha series,


series strfind = @rinstr(alpha1, "34")

fills the series with the last location (first from the end of the string) of the string “34” in
each string in ALPHA1, for each observation in the workfile sample.

Cross-references
See also @instr (p. 924) for finding substrings starting from the beginning of the string, and
@mid (p. 974) for extracting substrings.
@riwish—1079

@riwish Element Functions | String Functions

Inverse Wishart random draws.


Syntax: @riwish(S, n)
@riwishc(S, n)
@riwishi(S, n)
@riwishic(S, n)
@riwish(X, S, n)
@riwishc(X, S, n)
@riwishi(X, S, n)
@riwishic(X, S, n)
X: (optional) sym, p  p
S: sym, matrix, p  p
n: number, n  p – 1
Return: sym
–1
Draw a random symmetric inverse Wishart matrix using the W  W, n  density function.

The inverse Wishart density is given by

n
---
2
W
f  X W, n   ----------------------------------------------------------------------
–1
- (18.8)
np n  p  1- tr  WX 
------ ---------------------- -------------------------
n
G p  --- e
2 2 2
2 X
 2

where X and W are symmetric p  p matrices, and n  p – 1 .

There are four different forms of the function, corresponding to different ways of specifying
W . The forms are distinguished by different suffixes that are applied to the base “@rwish”
command and how they change the interpretation of the S matrix argument:
@riwish “” Supply W .
@riwishc “c” Supply the Cholesky decomposition of W .
This form is more efficient when performing multiple
draws from the same distribution (compute the Chole-
sky once, but sample many times).
1080—Function Reference: R

–1
@riwishi “i” Supply W .
This form is more efficient than explicitly inverting
–1
W to supply W .
–1
@riwishic “ic” Supply the Cholesky decomposition of W .
This form combines the efficiencies of the Cholesky
and inverse forms.

–1
Note that if X is an inverse Wishart random variable, then X is follows a Wishart distri-
bution:
–1 –1 –1
X  W p  W, n   X  Wp  W , n 

Examples
= @riwish(@identity(3), 5)

returns a random draw from the IW 3  I 3, 5  distribution.

Cross-references
See also @dwish (p. 856), @rwish (p. 1104), and @diwish (p. 840).

@rlaplace Element Functions | String Functions

Laplace distribution random draw.


Syntax: @rlaplace
Return: number

Draw a random value from the Laplace distribution with probability density function,
1 –x
f  x   --- e
2

Examples
= @rlaplace

returns a random draw from the Laplace distribution.

Cross-references
See also @claplace (p. 747), @dlaplace (p. 841), and @qlaplace (p. 1051).
@rlogistic—1081

@rlast By-Row Statistics

Last non-missing values in rows of group.

Value of the last non-missing value in each row of the group.


Syntax: @rlast(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


find the last non-missing value in the row.

Examples
show @rlast(g

returns a linked series of the last non-missing observations in the rows of group g.

Cross-references
See also @rfirst (p. 1073), @rifirst (p. 1075), and @rilast (p. 1076).

@rlogistic Element Functions | String Functions

Logistic distribution random draw.


Syntax: @rlogistic
Return: number

Draw a random value from the logistic distribution with probability density function,
–x
e
f  x   ------------------------
–x 2
1  e 

Examples
= @rlogistic

returns a random draw from the logistic distribution.

Cross-references
See also @clogistic (p. 748), @dlogistic (p. 843), and @qlogistic (p. 1052).
1082—Function Reference: R

@rlognorm Element Functions | String Functions

Log normal distribution random draw.


Syntax: @rlognorm(m, s)
m: number, m  0
s: number, s  0
Return: number

Draw a random value from the log normal error distribution with density function,
1 2 2
f  x m, s   ------------------- exp  –  log x – m    2s  
2
x 2ps
for x  0 and 0 otherwise.

Examples
= @rlognorm(0, 2)

returns a random draw from the log-normal(0, 2) distribution.

Cross-references
See also @clognorm (p. 749), @dlognorm (p. 843), and @qlognorm (p. 1052).

@rmax By-Row Statistics

Row maximums of group.

Maximum values across series in each row of the group.


Syntax: @rmax(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


find the maximum value across the data for the row.

Examples
show @rmax(g

returns a linked series of the maximums in the rows of group g.

Cross-references
See also @rmin (p. 1084), @rimax (p. 1077), and @rimin (p. 1077).
@rmedian—1083

@rmean By-Row Statistics

Row means of group.

Mean value across series in each row of the group.


Syntax: @rmeans(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


compute the mean of the values,
m
1
y t  ----
m  x jt
j1

Examples
show @rmean(g

returns a linked series of the means in the rows of group g.

Cross-references
See also @rmedian (p. 1083) and @rvar (p. 1102).

@rmedian By-Row Statistics

Row median of group.

Medians for each row of the group.


Syntax: @rmedian(x)
x: group
Return: series

For each observation t corresponding to a row in the group of m series, compute the
median of the m values  x 1t, , x mt  for the observation.

When m is odd, the median is the middle ordered-observation and when m is even, the
median is the average of the two middle ordered-observations. The median may be written
as

 x   m  1   2, t  m is odd
yt  
  x  m  2, t   x  m  2  1, t    2 m is even
1084—Function Reference: R

where the order statistics  x  1, t , x  2, t , , x  m, t   represent the data for observation t


ordered from low to high.

Examples
show @rmedian(g

returns a linked series of the medians in the rows of group g.

Cross-references
See also @rmean (p. 1083) and @rquantile (p. 1093).

@rmin By-Row Statistics

Row minimums of group.

Minimum values across series in each row of the group.


Syntax: @rmin(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


find the minimum value across the data for the row.

Examples
show @rmin(g

returns a linked series of the minimums in the rows of group g.

Cross-references
See also @rmax (p. 1082), @rimax (p. 1077), and @rimin (p. 1077).

@rmse Series Utility

Root of the mean of square error (difference) between series.

Computes the square root of the mean of the squared difference between x and y.
Syntax: @rmse(x, y, [s])
x: series
y: series
s: (optional) sample string or object
Return: number
@rmvnorm—1085

T
1 2
zt  ----
T   xt – yt 
t1

Examples
Let yf denote in-sample forecasts for the series y. Then
= @rmse(yf, y)

returns the RMSE between the series y and its forecast.

Cross-references
See also @mae (p. 959), @mape (p. 963), @mse (p. 1000), @smape (p. 1114), and @theil
(p. 1145).

@rmvnorm Matrix Utility

Multivariate normal random draws.


Syntax: @rmvnorm(S[, n])
@rmvnormc(S[, n])
@rmvnormi(S[, n])
@rmvnormic(S[, n])
m: (optional) vector
S: sym, matrix
n: (optional) integer, n  0
Return: vector, matrix

Draw random multivariate normals using the N  0, S  density function.

The multivariate normal density is given by


– --1-
1
exp  – --- xS x
2 –1
f  m, S   2pS
 2 

There are four different forms of the function, corresponding to different ways of specifying
S . The forms are distinguished by different suffixes that are applied to the base
“@rmvnorm” command and how they change the interpretation of the S matrix argument:
@rmvnorm “” Supply S .
@rmvnormc “c” Supply the Cholesky decomposition of S .
This form is more efficient when performing multiple
draws from the same distribution (compute the Chole-
sky once, but sample many times).
1086—Function Reference: R

–1
@rmvnormi “i” Supply S .
This form is more efficient than explicitly inverting
–1
S to supply S .
–1
@rmvnormic “ic” Supply the Cholesky decomposition of S .
This form combines the efficiencies of the Cholesky
and inverse forms.

If the optional argument n is omitted, the function returns a vector containing a single draw
from the distribution. If n is provided, n is the number of rows of the returned matrix, with each
row representing a draw from the distribution.

Examples
= @dmvnorm(@identity(3))

returns a random draw from a trivariate normal distribution.

Cross-references
See also @dmvnorm (p. 844).

@rnas By-Row Statistics

Number of missing observations in row of group.

Number of missing observations in each row of the group.


Syntax: @rnas(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


count the number of missing (NA) observations.

Examples
show @rnas(g

returns a linked series of the NA counts in the rows of group g.

Cross-references
See also @robs (p. 1088) and @rvalcount (p. 1101).
@rnorm—1087

@rnegbin Element Functions

Negative binomial distribution random draw.


Syntax: @rnegbin(n, p)
n: number, n  0
p: number, 0  p  1
Return: integer

Draw a random integer value from the negative binomial distribution with probability func-
tion,

 Gx  n x n
 ----------------------------------p  1 – p  x  0, 1, 
p  x n, p    G  x  1 G  n 
 0 otherwise

Examples
= @rnegbin(10, 0.5)

returns a random draw from the negative binomial(10, 0.5) distribution.

Cross-references
See also @cnegbin (p. 753), @dnegbin (p. 845), and @qnegbin (p. 1053).

@rnorm Element Functions

Standard normal distribution random draw.


Syntax: @rnorm
Return: number

Draw a random value from the standard normal distribution with probability density func-
tion,
–1  2 2
f  x    2p  exp  – x  2 

Examples
= @rnorm

returns a random draw from the standard normal distribution.

Cross-references
See also @cnorm (p. 753), @logcnorm (p. 950), @dnorm (p. 845), and @qnorm (p. 1054).
1088—Function Reference: R

@robs By-Row Statistics

Row numbers of non-missing observations in group.

Number of non-missing observations in each row of the group.


Syntax: @robs(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


count the number of non-missing observations.

Examples
show @robs(g

returns a linked series of the non-NA counts in the rows of group g.

Cross-references
See also @rnas (p. 1086) and @rvalcount (p. 1101).

@round Element Functions

Nearest integer, or value at given precision.

Return nearest integer or nearest decimal number at the given precision.


Syntax: @round(x[, n])
x: number
n: (optional) integer
Return: number

The decimal offset n may be interpreted as the precision to use when rounding the number.
• @round(x) returns the nearest integer to x. Numbers exactly midway between inte-
gers (e.g., 1.5 or 37.5) are rounded to next higher integer.
• @round(x, n) rounds to the nearest decimal number to x at the given precision:
n n
@round(x, n)  @round(x  10 )  10 .

If n is not an integer, the integer floor n will be used.

Examples
= @round(-97.5)
@rowextract—1089

returns -98.
= @round(@pi, 3)

returns 3.142.

Cross-references
See also @ceil (p. 737) and @floor (p. 887).

@rowextract Matrix Utility

Extract rowvector from matrix object.


Syntax: @rowextract(m, n)
m: matrix, sym
n: integer
Return: vector

Extract a vector from row n of the matrix object m, where m is a matrix object.

Note that we recommend that extraction be performed using the newer “.row” object data
member functions. See “Matrix Data Members” on page 556 and “Sym Data Members” on
page 992 in Object Reference and the examples below.

Examples
matrix m1 = @mnrnd(20, 5)
vector v1 = @rowextract(m1,3)

extracts row 3 from the matrix M1.


sym s1 = @unvech(@mnrnd(15))
vector v2 = @rowextract(s1, 5)

Alternately, using the data member functions, we have


vector v1a = m1.@row(3)
vector v1b = s1.@row(5)

Cross-references
See “Matrix Data Members” on page 556 and “Sym Data Members” on page 992 in Object
Reference.

See also @columnextract (p. 762) and @subextract (p. 1133).


1090—Function Reference: R

@rowranks Matrix Transformation

Matrix where each row contains ranks of the column values.


Syntax: @rowranks(m[, o, t])
m: matrix, vector
o: (optional) string
t: (optional) string
Return: matrix, vector

Returns a matrix where each row contains the rankings of the values of the corresponding
row of m.

The o option controls the direction of the ranking:


• “a” (ascending - default) or “d” (descending).

The t option controls tie-handling:


• Ties are broken according to the setting of t: “i” (ignore), “f” (first), “l” (last), “a”
(average - default), “r” randomize.

If you wish to specify tie-handling options, you must also specify the order option (e.g.,
@rowranks(x, "a", "i")).

Examples
= @rowranks(m1, "d")

returns a matrix whose i-th row ranks the elements in the i-th row of M1 so that the largest
element in said row has a rank of 1.

Cross-references
See also @sort (p. 1116), @colsort (p. 759), and @rowsort (p. 1091).

See also @ranks (p. 1064) and @colranks (p. 758).

See also @capplyranks (p. 733) and @rapplyranks (p. 1065).

@rows Matrix Utility

Number of rows.
Syntax: @rows(m)
m: matrix, vector, sym, series, group
Return: integer
@rowsort—1091

For series and groups @rows returns the number of observations in the workfile range.

Examples
matrix m1 = @mnrnd(10, 3)
scalar sc2 = @rows(m1)

assigns the value 10 to the scalar object SC2.


series q = nrnd
series r = nrnd
series s = nrnd
series t = nrnd
group mygrp q r s t
vector g = @fill(@rows(q), @columns(mygrp))

creates a two-element vector G containing the number of rows of Q and the number of series
in MYGRP.

Cross-references
See also @columns (p. 762).

@rowsort Matrix Utility

Matrix where each row contains sorted columns.


Syntax: @rowsort(m[, o])
m: matrix, vector
o: (optional) string
Return: matrix, vector

Returns a matrix where each row contains the sorted values of the corresponding row of m.

The option o controls the direction of the ranking: “a” (ascending - default) or “d” (descend-
ing).

Examples
Let M1 be a matrix. Then
= @rowsort(m1, "d")

returns a matrix whose i-th row is the sorted (from largest on the left to smallest on the
right) version of the i-th row in M1.

Cross-references
See also @sort (p. 1116) and @colsort (p. 759).
1092—Function Reference: R

See also @ranks (p. 1064), @colranks (p. 758), and @rowranks (p. 1090).

See also @capplyranks (p. 733) and @rapplyranks (p. 1065).

@rpareto Element Functions

Pareto distribution random draw.


Syntax: @rpareto(k, a)
k: number, k  0
a: number, a  0
Return: number

Draw a random value from the Pareto distribution with probability density function,

 0 xk
f  x k, a    a a1
  ak   x xk

Example
= @rpareto(1, 2)

returns a random draw from the Pareto(1, 2) distribution.

Cross-references
See also @cpareto (p. 769), @dpareto (p. 846), and @qpareto (p. 1054).

@rpoisson Element Functions

Poisson distribution random draw.


Syntax: @rpoisson(m)
m: number, m  0
Return: integer

Draw a random integer value from the Poisson distribution with probability function,

 x –m x  0, 1, , n, 
p  x m    m e  x!
 0 otherwise

Examples
= @rpoisson(10)

returns a random draw from the Poisson(10) distribution.


@rquantile—1093

Cross-references
See also @cpoisson (p. 770), @dpoisson (p. 846), and @qpoisson (p. 1055).

@rprod By-Row Statistics

Row products in group.

Product across series in each row of the group.


Syntax: @rsum(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


compute the product of the values,
m
yt   x jt
j1

Note that this function is prone to numeric overflow.

Examples
show @rprod(g

returns a linked series of the products of observations in the rows of group g.

Cross-references
See also @rsum (p. 1096).

@rquantile By-Row Statistics

Row quantiles in group.

Quantiles for each row of the group.


Syntax: @rquantile(x, q)
x group
q number, series
Return: series

For each observation t corresponding to a row in the group of m series, compute the q-
quantile of the m values  x 1t, , x mt  for the observation using the Rankit-Cleveland
quantile definition, for 0  q  1 .
1094—Function Reference: R

To compute the q -quantile, first find r , the smallest rank such that,
q  F  x r  

where the order statistics  x  1, t , x  2, t , , x  m, t   represent data for the m series ordered
from low to high, and F is the Rankit-Cleveland definition of the empirical distribution
function: F  x  r     r – 1  2   m . For purposes of computing F , tied ranks are assumed
to take the last tied value.

Then the quantile is computed as

 x  1, t  if F  x  1, t    q

y t    1 – d x  r – k, t   dx  r, t  if F  x  r – k, t    q  F  x  r – k, t  

 NA if F  x  t, t    q

where the interpolating constant is


q – F  x  r – k, t  
d  --------------------------------------------------------------
-
F  x  r – k, t   – F  x  r – k, t  

for k  0 the smallest integer where F  x  r – k, t    q . In the leading case where there are
no tied x  r – k, t  values, k  1 .

Examples
show @rquantile(g, 0.25

returns a linked series of the 25th percentiles in the rows of group g.

Cross-references
See also @rmedian (p. 1083).

@rstdev By-Row Statistics

Row sample (d.f. corrected) standard deviations.

Square roots of the Pearson product moment sample variances for each row of the group,
with d.f. correction.
Syntax: @rstdev(x)
x: group
Return: series

For each observation t corresponding to a row in the group of m series, compute the sam-
ple standard deviation,
@rstdevp—1095

m
1 2
yt  --------------
m–1   x jt – x .t 
j1

where x .t is the mean of the m values  x 1t, , x mt  for the observation.

Examples
show @rstdev(g

returns a linked series of sample standard deviations in the rows of group g.

Cross-references
See also @rstdevp (p. 1095) and @rstdevs (p. 1096).

@rstdevp By-Row Statistics

Row population (non d.f. corrected) standard deviations.

Square roots of (population) Pearson product moment population variances for each row of
the group, with no d.f. correction.
Syntax: @rstdevp(x)
x: group
Return: series

For each observation t corresponding to a row in the group of m series, compute the popu-
lation standard deviation,
m
1 2
yt  ----
m   x jt – x .t 
j1

where x .t is the mean of the m values  x 1t, , x mt  for the observation.

Examples
show @rstdevp(g

returns a linked series of population standard deviations in the rows of group g.

Cross-references
See also @rstdev (p. 1094) and @rstdevs (p. 1096).
1096—Function Reference: R

@rstdevs By-Row Statistics

Row sample (d.f. corrected) standard deviations.

Square roots of Pearson product moment sample variances for each row of the group, with
d.f. correction.
Syntax: @rstdevs(x)
x: group
Return: series

For each observation t corresponding to a row in the group of m series, compute the sam-
ple standard deviation,
m
1 2
yt  --------------
m–1   x jt – x .t 
j1

where x .t is the mean of the m values  x 1t, , x mt  for the observation.

Equivalent to @rstdev.

Examples
show @rstdevs(g

returns a linked series of sample standard deviations in the rows of group g.

Cross-references
See also @rstdev (p. 1094) and @rstdevp (p. 1095).

@rsum By-Row Statistics

Row sums.

Sum across series in each row of the group.


Syntax: @rsum(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


compute the sum of the values,
m
yt   x jt
j1
@rsweep—1097

Examples
show @rsum(g

returns a linked series of the sums of observations in the rows of group g.

Cross-references
See also @rprod (p. 1093) and @rsumsq (p. 1097).

@rsumsq By-Row Statistics

Row sums of squares.

Sums of squared values for each row of the group


Syntax: @rsumsq(x)
x: group
Return: series

For each observation t corresponding to a row  x 1t, , x mt  in the group of m series,


compute the sum of squared values,
m
2
yt   x jt
j1

Examples
show @rsumsq(g

returns a linked series of the sums of squares in the rows of group g.

Cross-references
See also @rsum (p. 1096).

@rsweep Matrix Algebra

Reverse sweep operator.

There are two syntaxes for @rsweep, one for the symmetric, and the other for then non-
symmetric operator.
Syntax: @rsweep(s[, n])
s: sym
k: integer
k2: (optional) integer
Return: matrix
1098—Function Reference: R

Returns the result of applying the symmetric sweep operator to symmetric matrix S at diago-
nal element k. If k2 is specified, sweeps on all diagonal elements between k and k2, inclu-
sive.

This is merely an alias for @sweep(s, k[, k2]), since the symmetric sweep operator is its
own reverse/inverse.
Syntax: @rsweep(m, r, c)
m: matrix, sym
r: integer
c: integer
Return: matrix

Returns the result of applying the reverse non-symmetric sweep operator to general matrix
M at element (r, c).

Let B  SWEEP k  A  be an application of the symmetric sweep operator. Then,


B kk  – 1  A kk , B ik  A ik  A kk where i  k , B kj  A kj  A kk where j  k , and
A ik A kj
B ij  A ij – ----------------
-
A kk

where i  k and j  k .

Let B  SWEEP rc  A  be an application of the non-symmetric sweep operator. Then,


B rc  1  A rc , B ic  A ic  A rc where i  r , B rj  – A rj  A rc where j  c , and
A ic A rj
B ij  A ij – ----------------
-
A rc

where i  r and j  c .

Examples
Consider a swept matrix replicating the results of an OLS regression (see @sweep function).
group g y x1 x2 x3
sym usscp = @inner(g)
sym s = @sweep(usscp, 2, 4)

Just as each application of the sweep operator effectively switched the role of a variable
from dependent to regressor, each application of the reverse sweep operator switches the
role of a variable from regressor back to dependent.

For example, we can remove X1 as a regressor for Y by applying @rsweep to the correspond-
ing diagonal element.
s = @rsweep(s, 2, 2)
@rtdist—1099

We can also verify these results against a standard equation object:


vector beta = @subextract(S, 3, 1, 4, 1) ' Regressor coefficients
scalar ssr = s(1,1) ' Sum of squared residuals
sym invXtX = -@subextract(s, 3, 3)
vector se = @sqrt(ssr * @getmaindiagonal(invXtX) / (@obssmpl - 2))
' Coefficient standard errors
equation eq.ls(noconst) y x2 x3

Cross-references
Goodnight, James H. (1979). “A Tutorial on the SWEEP Operator,” The American Statisti-
cian, 33, 149–158.

See also @sweep (p. 1140).

@rtdist Element Functions

Student’s t distribution random draw.


Syntax: @rtdist(v)
v: number, v  0
Return: number

Draw a random value from the Student’s t distribution with probability density function,
v1
G  ------------ v  1
–--------------------
 2  2
x  2
 
f  x v   --------------------------- 1  -----
1---   v 
2  v
 vp  G ---
 2

Examples
= @rtdist(1)

returns a random draw from the Cauchy distribution.

Cross-references
See also @ctdist (p. 775), @tdist (p. 1144), @dtdist (p. 847), and @qtdist (p. 1056).
1100—Function Reference: R

@rtrim Element Functions

Trim right whitespace of string.


Syntax: @rtrim(str)
str: string, alpha, svector
Return: string, alpha, svector

Returns the string str with spaces trimmed from the right.

Examples
@rtrim(" I doubt that I did it. ")

returns the string “ I doubt that I did it.”. Note that the spaces on the left remain.

If ALPHA1 is an alpha series,


alpha alphaltrim = @rtrim(alpha1)

returns the right-trimmed strings in ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


svector sveclen = @ltrim(svec1)

returns a string vector containing the right-trimmed elements of SVEC1.

Cross-references
See also @ltrim (p. 953) and @trim (p. 1153).

@runif Element Functions

Uniform distribution random draw.


Syntax: @runif(a, b)
a: number
b: number, b  a
Return: number

Draw a random value from the uniform distribution with probability density function,
1
f  x a, b   ------------ axb
b–a
and 0 otherwise.
@rvalcount—1101

Examples
= @runif(1, 6)

returns a random draw from the continuous uniform(1, 6) distribution.

Cross-references
See also @cunif (p. 806), @dunif (p. 849), and @qunif (p. 1059).

@runpath Support Functions

Syntax: @runpath
Return: string

Returns a string containing the location of the program currently being executed. If @run-
path is being executed as a child program from a parent as part of an include or exec
statement, the string will return the location of the parent program.

Examples
If the program d:\myprogs\program1.prg has the line:
string y = @runpath

then y will contain “D:\MYPROGS\PROGRAM1.PRG”, if program1 is run by itself, and will


return the location of the parent program otherwise.

Cross-references
See also @linepath (p. 944), @evpath (p. 878) and @temppath (p. 1145).

@rvalcount By-Row Statistics

Number of matching values in rows.


Syntax: @rvalcount(x, v)
x: group
v: number, series
Return: series

The number of observations with a value equal to v in each row of the group.

Examples
show @rvalcount(g, 1

returns a linked series of counts of the number 1 in the rows of group g.


1102—Function Reference: R

Cross-references
See also @rnas (p. 1086) and @robs (p. 1088).

@rvar By-Row Statistics

Row population (non d.f. corrected) variances.

Pearson product moment population variances for each row of the group, with d.f. correc-
tion.
Syntax: @rvars(x)
x: group
Return: series

For each observation t corresponding to a row in the group of m series, compute the popu-
lation variance,
m
1 2
y t  ----
m   x jt – x .t 
j1

where x .t is the mean of the m values  x 1t, , x mt  for the observation.

Examples
show @rvar(g

returns a linked series of population variances in the rows of group g.

Cross-references
See also @rmean (p. 1083).

See also @rvarp (p. 1102) and @rvars (p. 1103).

@rvarp By-Row Statistics

Row population (non d.f. corrected) variances.

Pearson product moment population variances for each row of the group, with d.f. correc-
tion.
Syntax: @rvars(x)
x: group
Return: series
@rvars—1103

For each observation t corresponding to a row in the group of m series, compute the popu-
lation variance,
m
1 2
y t  ----
m   x jt – x .t 
j1

where x .t is the mean of the m values  x 1t, , x mt  for the observation.

Examples
show @rvarp(g

returns a linked series of population variances in the rows of group g.

Cross-references
See also @rvar (p. 1102) and @rvars (p. 1103).

@rvars By-Row Statistics

Row sample (d.f. corrected) standard deviations.

Pearson product moment population variances for each row of the group, with d.f. correc-
tion.
Syntax: @rvars(x)
x: group
Return: series

For each observation t corresponding to a row in the group of m series, compute the sam-
ple variance,
m
1 2
y t  --------------
m–1   x jt – x .t 
j1

where x .t is the mean of the m values  x 1t, , x mt  for the observation.

Examples
show @rvars(g

returns a linked series of sample variances in the rows of group g.

Cross-references
See also @rvar (p. 1102) and @rvarp (p. 1102).
1104—Function Reference: R

@rweib Element Functions

Weibull distribution random draw.


Syntax: @rtdist(m, a)
m: number, m  0
a: number, a  0
Return: number

Draw a random value from the Weibull distribution with probability density function,
–a a – 1 a
f  x m, a   am x exp  –  x  m  

for x  0 and 0 elsewhere.

Examples
= @rweib(1, 1)

returns a random draw from the Weibull(1, 1) distribution.

Cross-references
See also @cweib (p. 808), @dweib (p. 855), and @qweib (p. 1060).

@rwish Matrix Utility

Wishart random draw.


Syntax: @rwish(S, n)
@rwishc(S, n)
@rwishi(S, n)
@rwishic(S, n)
X: (optional) sym, p  p
S: sym, matrix, p  p
n: number, n  p – 1
Return: sym

Draw a random symmetric Wishart matrix using the W p  S, n  density function.

The Wishart density is given by


@rwish—1105

n – p – 1-
---------------------
2
X
f  X S, n   ------------------------------------------------------
–1
-
np n tr  S X 
------ --- ------------------------
n
S G p  --- e
2 2 2
2
 2

where X and S are symmetric p  p matrices, and n  p – 1 .

There are four different forms of the function, corresponding to different ways of specifying
S . The forms are distinguished by different suffixes that are applied to the base “@rwish”
command and how they change the interpretation of the S matrix argument:
@rwish “” Supply S .
@rwishc “c” Supply the Cholesky decomposition of S .
This form is more efficient when performing multiple
draws from the same distribution (compute the Chole-
sky once, but sample many times).
–1
@rwishi “i” Supply S .
This form is more efficient than explicitly inverting
–1
S to supply S .
–1
@rwishic “ic” Supply the Cholesky decomposition of S .
This form combines the efficiencies of the Cholesky
and inverse forms.

X  W p  S, n  is generally thought of as the accumulated scatter matrix of n random draws


from N  0, S  , i.e., x i  N  0, S  ,
n
X   xi xi  ,
i1

though the mathematical definition has been extended to cover real-valued n.


–1
Note that if X is a Wishart random variable, then X follows an inverse Wishart distribu-
tion:
–1 –1
X  W p  S, n   X  Wp  S , n 

Examples
= @rwish(@identity(3), 5)

returns a random draw from the W 3  I 3, 5  distribution.

Cross-references
See also @dwish (p. 856), @diwish (p. 840), and @riwish (p. 1079).
1106—Function Reference: R
Function Reference: S—1107

Function Reference: S
@scale ..................Scale rows or columns of matrix (p. 1108).
@seas ...................Seasonal dummy variable (p. 1109).
@second ...............seconds of the minute of the observation (p. 1109).
@seq ....................Vector containing arithmetic sequence (p. 1110).
@seqm .................Vector containing geometric sequence (p. 1111).
@sfill....................Create a string vector from a list of strings (p. 1111).
@sign ...................Sign of number (p. 1112).
@sin.....................Sine function in radians (p. 1112).
@skew .................Skewness (p. 1113).
@skewsby ............Skewness for a series for each specified group (p. 1114).
@smape................Symmetric mean absolute percentage error (difference) between
series (p. 1114).
@solvesystem .......Solve system of linear equations (p. 1115).
@sort....................Sort elements of data object (p. 1116).
sqr ........................Square root (p. 1116).
@sqrt....................Square root (p. 1117).
@stdev .................Sample standard deviation (d.f. adjusted) (p. 1117).
@stdevp................Population standard deviation (no d.f. adjustment) (p. 1118).
@stdevpsby ..........Population standard deviations (d.f. corrected) for a series for each
specified group (p. 1119).
@stdevs ................Sample standard deviation (d.f. adjusted) (p. 1119).
@stdevsby ............Sample standard deviations (d.f. corrected) for a series for each
specified group (p. 1120).
@stdevssby...........Sample standard deviations (d.f. corrected) for a series for each
specified group (p. 1120).
@stdize ................Standardized data (using sample standard deviation) (p. 1121).
@stdizep...............Standardized data (using population standard deviation) (p. 1122).
@str .....................String representation of number (p. 1123).
@strdate ...............String corresponding to the date of the observation (p. 1128).
@stripcommas ......Remove leading and trailing commas surrounding string (p. 1129).
@stripparens.........Remove paired leading and trailing parentheses surrounding string
(p. 1130).
@stripquotes.........Remove paired double-quotation marks surrounding string
(p. 1131).
@strlen.................Length of string (p. 1132).
@strnow...............String representation of the current date and time (p. 1132).
@subextract..........Extract submatrix from matrix object (p. 1133).
1108—Function Reference: S

@sum .................. Arithmetic sum (p. 1135).


@sumsby ............. Sum of observations in a series for each specified group (p. 1136).
@sumsq ............... Arithmetic sum of squares (p. 1136).
@sumsqsby.......... Sum of squared observations in a series for each specified group
(p. 1137).
@svd ................... Singular value decomposition (economy) of matrix (p. 1137).
@svdfull .............. Singular value decomposition (full) of matrix (p. 1139).
@sweep ............... Sweep operator (p. 1140).

@scale

Scale rows or columns of matrix.


Syntax: @scale(m, v[,p])
m: matrix, sym
v: vector
p: (optional) number
Return: matrix or sym

Scale the rows or columns of a matrix, or the rows and columns of a sym matrix.
• If m is a matrix and v is a vector, the i-th row of m will be scaled by the i-th element
of v, optionally raised to the power p (row scaling). The length v must equal the num-
ber of rows of m.
• If m is a matrix and v is a rowvector, the i-th column of m will be scaled by the i-th
element of v, optionally raised to the power p (column scaling). The length v must
equal the number of columns of m.
• If m is a sym object, then v may either be a vector or a rowvector. The (i,j)-th element
of m will be scaled by both the i-th and j-th elements of v (row and column scaling).
The length v must equal the number of rows (and columns) of m.

Let M be the matrix object, V be the vector or rowvector, and L  diag  V 1, V 2, , V p  be


the diagonal matrix formed from the elements of V. Then @scale(m, v, p) returns:
p
• L M , if M is a matrix and V is a vector.
p
• ML , if M is a matrix and V is a rowvector.
p p
• L ML , if M is a sym matrix.

Examples
sym covmat = @cov(grp1)
vector vars = @getmaindiagonal(covmat)
@second—1109

sym corrmat = @scale(covmat, vars, -0.5)

computes the covariance matrix for the series in the group object GRP1, extracts the vari-
ances to a vector VARS, then uses VARS to obtain a correlation matrix from the covariance
matrix.

Cross-references
See also @cov (p. 767).

@seas

Seasonal dummy variable.


Syntax: @seas(x)
x: integer
Return: series

Returns the seasonal dummy variable series in a quarterly or monthly workfile, indicating
whether the date in the workfile of each observation matches the seasonal value specified in
x.

Examples
workfile m 2020 2022
series m2 = @seas(2)

creates a dummy variable series with February observations (seasonal 2) equal to 1.


workfile q 2020 2021
smpl if @seas(2) = 1

creates a quarterly workfile, then sets the sample to include only observations in the second
quarter.

Cross-references
See also @month (p. 983), @quarter (p. 1059).

@second

Seconds of the minute of the observation.


Syntax: @second
Return: series

Returns the seconds of the minute (0–59) associated with each observation in the workfile.
1110—Function Reference: S

• If the workfile is of lower than second frequency, all observations will be set to 0.
• If the workfile is undated, observations will be set to -1.

Examples
series dt = @second
saves the seconds of the minute into the series DT.
The command
smpl if @second = 59
sets the sample to only include observations for the last second of the minute.

Cross-references
See also @day (p. 826), @hour (p. 910), @hourf (p. 910), @minute (p. 978), @month
(p. 983), @seas (p. 1109), @weekday (p. 1192), @quarter (p. 1059), and @year (p. 1223).

@seq

Vector containing arithmetic sequence.


Syntax: @seq(d1, d2, n)
d1: number
d2: number
n: integer
Return: vector

Returns a vector holding an arithmetic sequence of n elements. The initial element has value
d1, and the difference between each element and its predecessor is d2.

Examples
vector v1 = @seq(0, 1/3, 10)

creates V1, a 10-element vector with first element 0, and each subsequent element increas-
ing by 1/3.
vector cdf1 = @cnorm(@seq(-2.0, 0.01, 401))

create a 401-element vector of values of the normal CDF evaluated at points from -2.0 to 2.0

Cross-references
See also @grid (p. 897), @range (p. 1063), and @seqm (p. 1111).
@sfill—1111

@seqm

Vector containing geometric sequence.


Syntax: @seqm(d1, d2, n)
d1: number
d2: number
n: integer
Return: vector

Returns a vector holding a geometric sequence of n elements. The initial element has value
d1, and the ratio between each subsequent element and its predecessor is d2.

Examples
vector v1 = @seqm(1, 2, 10)

creates a V1, a 10-element vector with first element 1, and each subsequent element repre-
senting a power of 2.

Cross-references
See also @grid (p. 897), @range (p. 1063), and @seq (p. 1110).

@sfill

Create a string vector from a list of strings.


Syntax: @sfill(str1[, str2, str3, ...])
str1: string
strs: string str2, str3, ...
Return: svector

Returns an svector containing strings specified in a comma separated list of strings.

Examples
If string list SS01 contains “A B C D E F”, then
svector s1 = @sfill("A", "B", "C", "D", "E", "F")

returns the 6 element svector S1, where row one of S1 contains “A”, row two contains “B”,
etc.
svector s2 = @sfill("my apples", "your oranges", "our pears")
1112—Function Reference: S

creates a 3 element svector S2, with the rows containing “my apples”, “your oranges”, and
“our pears”.

Cross-references
See also @wsplit (p. 1216). See @wjoin (p. 1202) for obtaining a string from an svector.

@sign

Sign of number.
Syntax: @sign(x)
x: number
Return: integer

Returns sign of x: -1, 0, 1 depending on the sign of x (“<0”, “=0”, “>0”).

Examples
= @sign(1.23)

returns 1.
matrix m1 = @round(@mnrnd(30, 2))
matrix m2 = @sign(m1)

produces a 30  2 matrix of -1, 0, and 1 depending on the sign of the corresponding ele-
ment of the randomly generated matrix M1.
vector v1 = @round(@mnrnd(30))
vector v2 = @sign(v1)

produces a 30 -element sign vector corresponding to V1.

Cross-references
See also @egt (p. 863), @eeq (p. 861), and @elt (p. 867).

@sin Element Functions

Sine function in radians.

Compute the sine of x (specified in radians).


Syntax: @asin(x)
x: number
Return: number
@skew—1113

Examples
= @sin(@pi/2)

returns 1.

Cross-references
See also @acos (p. 714), @asin (p. 717), @atan (p. 718), @cos (p. 766), and @tan (p. 1144).

@skew

Skewness.

Computes the skewness of the elements of x.


Syntax: @skew(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

The skewness is calculated as


T 3
1 xt – x
y  ----
T   -------------
ĵ 

t1

where x is the sample mean, and ĵ is an estimator for the standard deviation that is based
on the biased estimator for the variance
T
1 2
ĵ  ----
T   xt – x 
t1

The skewness of a symmetric distribution, such as the normal distribution, is zero. Positive
skewness means that the distribution has a long right tail and negative skewness implies
that the distribution has a long left tail.

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x = @nrnd, then
= @skew(x)

returns a value close to 0 in large samples (since the normal distribution is symmetric).
1114—Function Reference: S

Cross-references
See also @mean (p. 971), @var (p. 1179), and @kurt (p. 936).

@skewsby

Skewness for a series for each specified group.


Syntax: @skewsby(x, y[y1, y2, ... yn, s])
x: series
y: series, alpha
s: (optional) sample string or object
Return: series

Returns the skewnesses of x for each group defined by distinct values of y.

EViews will use the current or specified workfile sample.

Examples
show @skewsby(x, g1, g2)

produces a linked series of the by-group sample skews of the series x, where members of the
same group have identical values for both g1 and g2.

Cross-references
See also @skew (p. 1113) and @kurtsby (p. 937).

@smape

Symmetric mean absolute percentage error (difference) between series.

Computes the mean of the symmetric absolute percentage difference between x and y.
Syntax: @smape(x, y, [s])
x: series
y: series
s: (optional) sample string or object
Return: number

1 T xt – yt
z t  100  ----
T  ----------------------------------
 xt  yt   2
-
t1

EViews will use the current or specified workfile sample.


@solvesystem—1115

Examples
Let yf denote in-sample forecasts for the series y. Then
= @smape(yf, y)

returns the SMAPE between the series y and its forecast.

Cross-references
See also @mae (p. 959), @mape (p. 963), @mse (p. 1000), @rmse (p. 1084), and @theil
(p. 1145).

@solvesystem

Solve system of linear equations.


Syntax: @solvesystem(o, v)
m: matrix, sym
v: vector
Return: vector

Returns the vector x that solves the linear system Mx  v where the matrix or sym M is
given by the argument m, and the vector is given by the argument v.

Examples
We first create a workfile, generate a random series, and create a group for estimating a
trend regression.
workfile u 100
series y = nrnd
group g 1 @trend

We extract the moment matrices,


matrix xx = @inner(g)
vector xy = @transpose(@convert(g)) * @convert(y)
and solve the moment conditions to obtain regression coefficient estimates
vector b1 = @solvesystem(xx, xy)

We may compare these results to those obtained by estimation using series and the equation
object:
equation eq1.ls y g
vector b2 = eq1.@coefs

and see that B1 and B2 are identical.


1116—Function Reference: S

Cross-references
See also @regress (p. 1069), @intercept (p. 925), and @trendcoef (p. 1151).

@sort

Sort elements of matrix or vector.


Syntax: @sort(m[, o])
m: matrix or vector
o: (optional) string
Return: matrix, vector

Returns a matrix or vector containing the sorted elements of the matrix or vector object m.

Note that sorting a matrix ranks every element of the matrix and arranges the results to
match the elements of the original matrix, from upper left to lower right.

The o option controls the direction of the ranking:


• “a” (ascending - default) or “d” (descending)

Examples
Let M1 be an m  n matrix. Then
= @sort(m1, "d")

returns an m  n matrix whose elements are those of M1, sorted from largest to smallest in
column-major order.

Cross-references
See also @colsort (p. 759) and @rowsort (p. 1091).

See also @ranks (p. 1064), @colranks (p. 758), and @rowranks (p. 1090).

See also @capplyranks (p. 733) and @rapplyranks (p. 1065).

sqr Element Functions

Square root.
Syntax: sqr(x)
x: number
Return: number

Returns the square root, for x > 0.


@stdev—1117

Examples
= sqr(9)

returns 3.

Cross-references
See also @sqrt (p. 1117).

@sqrt Element Functions

Square root.
Syntax: @sqrt(x)
x: number
Return: number

Returns the square root, for x > 0.

Examples
= @sqrt(9)

returns 3.

Cross-references
See also sqr (p. 1116).

@stdev

Sample standard deviation (d.f. adjusted).

Square root of sample (d.f. adjusted) Pearson product moment variance.


Syntax: @stdev(x, [s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

The sample standard deviation is calculated as


T
1 2
STDEV  -------------
T–1   xt – x 
t1

where x is the mean of x .


1118—Function Reference: S

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x = @nrnd, then
= @stdev(x)

returns a value near 1 in large samples.

Cross-references
See also @stdevp (p. 1118), @stdevs (p. 1119), and @var (p. 1179).

@stdevp

Population standard deviation (no d.f. adjustment).

Square root of population (non-d.f. adjusted) Pearson product moment variance.


Syntax: @stdevp(x, [s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

The population standard deviation is calculated as


T
1 2
STDEVP  ----
T   xt – x 
t1

where x is the mean of x .

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x = @nrnd, then
= @stdevp(x)

returns a value near 1 in large samples.

Cross-references
See also @stdev (p. 1117), @stdevs (p. 1119), and @varp (p. 1179).
@stdevs—1119

@stdevpsby

Population standard deviations (d.f. corrected) for a series for each specified group.
Syntax: @stdevspby(x, y[y1, y2, ... yn, s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Returns the population Pearson product moment standard deviations (d.f. corrected) for x
each group defined by distinct values of y.

EViews will use the current or specified workfile sample.

Examples
show @stdevpsby(x, g1, g2)

produces a linked series of the by-group population standard deviations of the series x,
where members of the same group have identical values for both g1 and g2.

Cross-references
See also @stdevsby (p. 1120) and @stdevssby (p. 1120).

@stdevs

Sample standard deviation (d.f. adjustment).

Square root of sample (d.f. adjusted) Pearson product moment variance.


Syntax: @stdevs(x, [s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

Equivalent to @stdev.

For series calculations, EViews will use the current or specified workfile sample.

Examples
x = @nrnd
= @stdevs(x)
1120—Function Reference: S

returns a value near 1 in large samples.

Cross-references
See also @stdev (p. 1117), @stdevp (p. 1118), and @vars (p. 1181).

@stdevsby

Sample standard deviations (d.f. corrected) for a series for each specified group.
Syntax: @stdevsby(x, y[y1, y2, ... yn, s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Returns the sample standard deviations (d.f. corrected) for x each group defined by distinct
values of y.

EViews will use the current or specified workfile sample.

Examples
show @stdevsby(x, g1, g2)

produces a linked series of the by-group sample standard deviations of the series x, where
members of the same group have identical values for both g1 and g2.

Cross-references
See also @stdevpsby (p. 1119) and @stdevssby (p. 1120).

@stdevssby

Sample standard deviations (d.f. corrected) for a series for each specified group.
Syntax: @stdevssby(x, y[y1, y2, ... yn, s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Returns the Pearson product moment sample standard deviations (d.f. corrected) for x each
group defined by distinct values of y.

EViews will use the current or specified workfile sample.


@stdize—1121

Examples
show @stdevssby(x, g1, g2)

produces a linked series of the by-group sample standard deviations of the series x, where
members of the same group have identical values for both g1 and g2.

Consider the commands


matrix m = @mrnd(100,100)
@mean(m)
@vars(m)
matrix stdm = @stdize(m)
@mean(stdm)
@vars(stdm)

The matrix M should have mean approximately 0.5 and sample variance approximately
0.083. The standardized matrix, STDM, should have mean approximately 0 and sample vari-
ance of 1.

Cross-references
See also @stdevsby (p. 1120) and @stdevpsby (p. 1119).

@stdize

Standardized data (using sample standard deviation).

Return copy of data scaled and translated to have a mean of zero and a Pearson product
moment sample standard deviation of one.
Syntax: @stdize(x, [s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: series, vector, matrix object

The adjusted data are calculated as


xt – x
y t  -------------

where x and ŝ are the mean and sample standard deviation, respectively, of x .

For series calculations, EViews will use the current or specified workfile sample.

Examples
show @stdize(x)
1122—Function Reference: S

returns a linked series of the standardized values of x.

Consider the commands


matrix m = @mrnd(100,100)
@mean(m)
@varp(m)
matrix stdm = @stdizep(m)
@mean(stdm)
@varp(stdm)

The matrix M should have mean approximately 0.5 and population variance approximately
0.083. The standardized matrix, STDM, should have mean approximately 0 and population
variance of 1.

Cross-references
See also @stdizep (p. 1122), @colstdize (p. 760) and @colstdizep (p. 761).

@stdizep

Standardized data (using population standard deviation).

Return copy of data scaled and translated to have a mean of zero and a population (non-d.f.
adjusted) Pearson product moment standard deviation of one.
Syntax: @stdizep(x, [s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: series, vector, matrix object

The adjusted data are calculated as


xt – x
y t  -------------

where x and ĵ are the mean and population standard deviation, respectively, of x .

For series calculations, EViews will use the current or specified workfile sample.

Examples
show @stdize(x)

returns a linked series of the standardized values of x.

Consider the commands


@str—1123

matrix m = @mrnd(100,100)
@mean(m)
@varp(m)
matrix stdm = @stdizep(m)
@mean(stdm)
@varp(stdm)

The matrix M should have mean approximately 0.5 and population variance approximately
0.083. The standardized matrix, STDM, should have mean approximately 0 and population
variance of 1.

Cross-references
See also @stdize (p. 1121), @colstdize (p. 760) and @colstdizep (p. 761).

@str Element Functions

String representation of number.


Syntax: @str(d[, fmt])
d: number
fmt: (optional) numeric format string
Return: string

Returns a string representing in d. You may provide an optional format string, fmt.

By default, EViews will format the number string using 10 significant digits, with no leading
or trailing characters, no thousands separators, and an explicit decimal point.

(The default conversion is equivalent to using @str with the format “g.10” as described
below.)

You may provide an explicit format string fmt to write your number in a specific fashion. A
numeric format string has the format:
[type][t][+][(][$][#][<|=|>][0][width][[.|..]precision][%][)]
There are a large number of syntax elements in this format but we may simplify matters
greatly by dividing them into four basic categories:
• format: [type]
• width: [<|=|>][width]
• precision: [precision]
1124—Function Reference: S

• advanced modifiers: the remaining elements (leading and trailing characters, padding
and truncation modifiers, separators, display of negative numbers)

The type, width, and precision components are the basic components of the format so we
will focus on them first. We describe the advanced modifiers in “Modified Formats” on
page 1126.

Basic Formats
EViews offers formats designed for both real-valued and integer data.

Basic Real-Value Formats


The basic real-value format is:
[type][<|=|>][width][.][precision]
The type component is a single character indicating the basic type and the width and preci-
sion arguments are numbers indicating the number of output characters and the precision at
which the numbers should be written. If specified, the precision should be separated from
the type and width portion of the format by a “.” character (or “..” as we will see in “Modi-
fied Formats” on page 1126).

If you specify a format with neither width nor precision, EViews will format the number at
full precision with matching string width.

The following types are for use with real-valued data:

g significant digits
z significant digits with trailing zeros
c fixed characters with single leading space for posi-
tive numbers
f fixed decimal places
e scientific/float
p percentage (same as “f” but values are multiplied
by 100)
s suppressed decimal point format
r ratio, e.g., “30 1/5”

The type character may be followed by a width specification, consisting of a width indicat-
ing the number of output characters, optionally preceded by a “>”, “=” or “<” modifier.
• If no width is provided, the number will be rendered in a string of the exact length
required to represent the value (e.g., the number 1.23450 will return “1.2345”, a
string of length 6).
@str—1125

• If an unmodified width or one with the “>” modifier is provided, the specified num-
ber places a lower-bound on the width of the string: the output will be left-padded to
the specified width, if necessary, otherwise the string will be lengthened to accommo-
date the full output. By default, padding will use spaces, but you may elect to use 0’s
by providing an advanced modifier (“Modified Formats” on page 1126).
• If the“<” modifier is provided along with width, the width places an upper-bound on
the width of the string: the output will not be padded to the specified width. If the
number of output characters exceeds the width, EViews will return a width-length
string filled with the “#” character.
• If the“=” modifier is provided along with width, the width provides an exact-bound
for the width of the string: the output will be padded to specified width, if necessary.
If the number of characters exceeds the width, EViews will return a width-length
string filled with the “#” character.

If you specify a precision, the interpretation of the value will vary depending on the format
type. For example, precision represents the number of significant digits in the “g” and “z”
formats, the number of characters in the “c” format, and the number of digits to the right of
the decimal in the “f”, “e”, “p”, and “s” formats. For the “r” format, the precision deter-
mines maximum denominator for the fractional portion (as a power-of-10).

The following guidelines are used to determine the precision implied by a number format:
• If you specify a format with only a precision specification, the precision will implicitly
determine the width at which your numbers are written.
• If you specify a format with only a width specification, the width will implicitly deter-
mine the precision at which your numbers are written. Bear in mind that only the
modified width specifications “=width” and “<width” impose binding restrictions
on the precision.
• If you specify a format using both width and precision, the precision at which your
numbers are written will be determined by whichever setting is most restrictive (i.e.,
“f=4.8” and “f=4.2” both imply a formatted number with two digits to the right of
the decimal).)

Basic Integer Formats


The basic integer format is:
[type][<|=|>][width]
The type component is a single character indicating the basic type. The following types are
for use with integer data:
1126—Function Reference: S

i integer
h hexadecimal
o octal
b binary

If one of the integer formats is used with real-valued data, the non-integer portion of the
number will be ignored. You may specify a width using the syntax and rules described in
“Basic Real-Value Formats” on page 1124.

Modified Formats
Recall that the syntax of a numeric format string is given by:
[type][t][+][(][$][#][<|=|>][0][width][[.|..]precision][%][)]
In addition to the basic type, width, and precision specifiers, the formats take a set of modifi-
ers which provide you with additional control over the appearance of your output string:
• You may combine any of the real-value format characters (“g”, “e”, “f”, etc.) with the
letter “t” (“gt”, “et”, “ft”, etc.) to display a thousands separator (“1,234.56”). By
default, the separator will be a comma “,”, but the character may be changed to a “.”
using the “..” format as described below.
• You may add a “+” symbol after the format character (“g+”, “et+”, “i+”) to display
positive numbers with a leading “+”.
• To display negative numbers within parentheses, you should enclose the remaining
portion of the format in parentheses “ft+($8.2)”.
• Add “$” to the format to display a leading “$” currency character.
• You should include a “#” to display a trailing point in scientific notation (e.g.,
“3.e+34”).
• The width argument should include a leading zero (“0”) if you wish padded numbers
to display leading zeros instead of spaces (“g08.2”, “i05”).
• If you added a “t” character to your real-value format type, you may replace the usual
“.” width-precision separator with “..” (“ft<08..2”, “e=7..”, “g..9”, etc.) to reverse the
thousands and decimal separators so that thousands will be separated by a “.” and
decimal portion by a “,” (“1.234,56”).
• Adding a “%” character to the end of the format adds the “%” character to the end of
the resulting string.

Examples
string num = @str(1.23)
@str—1127

assigns to the string NUM the text “1.23”.


alpha alpha1 = @str(-123.88)

assigns the string “-123.88” to the alpha series ALPHA1.


string num = @str(123456,"z.9")

returns a string formatted to 9 significant digits with trailing zeros: “123456.000”.


string num = @str(123456,"z.4")

returns a string formatted to 4 significant digits with trailing zeros: “1.235e+05”. Note that
since the input number has more than 4 significant digits, no trailing zeros are added and
the resulting string is identical to one that would have been produced with a “g.4” format.
string num = @str(126.543,"c.7%")

returns a string with exactly 7 characters, including a leading space, and a trailing percent
sign: “ 126.5%”.
string num = @str(126.543,"p.7")

converts the number 126.543 into a percentage with 7 decimal places and returns
“12654.3000000”. Note no percent sign is included in the string.
string num = @str(1.83542,"f$5.4")

returns “$1.8354”. The width selection of “5” with an implicit “>” modifier is irrelevant,
since the precision setting of “4”, coupled with the insertion of the “$” symbol yields a
string with more characters than “5”.
string num = @str(1.83542,"f$8.4")

returns “ $1.8354”. Here the width selection is binding, and a leading space has been added
to the string.
string num = @str(1.83542,"f$=5.4")

returns “ $1.84”. The explicit “=” width modifier causes the width setting of “5” to be bind-
ing.
string num = @str(524.784,"r")

converts the number 524.784 into a ratio representation: “524 98/125”.


string num = @str(1784.321,"r=3")

will return “###”, since there is no way to represent 1784.321 as a string with only 3 charac-
ters.
string num = @str(543,"b")

converts the number 543 into a binary representation: “1000011111”.

The matrix command


1128—Function Reference: S

svector svec1 = @str(v1)

converts the numeric values of vector V1 to strings and puts the results in the svector
SVEC1. If the svector SVEC1 exists it will be sized to match the rows of V1 and missing val-
ues will be converted to empty strings.

The series command


alpha a1 = @val(gdp)

creates the alpha series A1 and converts the numeric values of series GDP to string. NA val-
ues will be become empty strings.

Format strings may be used to govern the conversion,


svector svbin = @str(vec1, "e")

converts the numeric values in the vector VEC1 into their strings representation in scientific
notation and assigns them to the svector SVBIN.

Cross-references
See @val (p. 1175) to interpret strings as numbers.

@strdate

String representation of the dates of the observation.


Syntax: @strdate(fmt)
fmt: date format string
Return: alpha

Fill an alpha series with workfile dates as strings, using the date format string fmt, for each
observation in the workfile sample. Only observations in the workfile sample will be filled.

Date format syntax is outlined in “Date Formats” on page 106.

@strdate is a specialized form of a call to the @datestr (p. 824) function, applied to all of
the observations in the workfile.

Examples
The commands
alpha wfdates1 = @strdate("yyyy/mm/dd")
alpha wfdates2 = @datestr(@date, "yyyy/mm/dd")

fill the alpha series WFDATES1 and WFDATES2 with the corresponding workfile dates in
“yyyy/mm/dd” format.
alpha hmsdates = @strdate("yyyy-MM-DD HH:mi:ss")
@stripcommas—1129

fills the alpha series HMSDATES with the workfile dates in "yyyy-MM-DD HH:mi:ss" format.

Cross-references
See @datestr (p. 824) and @strnow (p. 1132) for other functions to obtain date strings.

See @dateval (p. 825) for converting date strings to date numbers.

@stripcommas Element Functions

Remove leading and trailing commas surrounding string.


Syntax: @stripcommas(str)
str: string
Return: string

Returns the contents of the string str with leading and trailing commas (ignoring
whitespace) stripped.

Leading and trailing commas are always removed, even if unpaired. All whitespace charac-
ters up to the leading comma and whitespace characters after the trailing comma are also
removed.

Examples
Define the string object
string s1 = " , lettuce, tomato, onion, "

so that S1 contains the string “ , lettuce, tomato, onion, ”. Note the presence of the
whitespace before the leading, and after the trailing comma.

Then the commands


string sc1 = @stripcommas(" , lettuce, tomato, onion, ")
string sc2 = @stripcommas(s1)

create SC1 and SC2 which contain the string “ lettuce, tomato, onion”. Note that the result-
ing string retains the space (“ ”) after the initial comma, but not the space after the last
comma in S1.

If ALPHA1 is an alpha series, the command


alpha a1 = @stripcommas(alpha1)

fills A1 with strip-comma values of ALPHA1 for each observation in the workfile sample.

If AVEC1 is an svector, the commands


svector as1 = @stripcommas(avec1)
1130—Function Reference: S

svector as2 = @stripcommas(avec1.@rows(@fill(1, 3, 5))

create svectors AS1 and AS2, where AS1 contains double-quoted values of AVEC1, and AS2
contains double-quoted values of the rows 1, 3, and 5 of AVEC1.

Cross-references
See also @stripparens (p. 1130) and @stripquotes (p. 1131).

@stripparens Element Functions

Remove paired leading and trailing parentheses surrounding string.


Syntax: @stripparens(str)
str: string
Return: string

Returns the contents of the string str with parentheses (“( )”) stripped from both the left and
the right ends. If a parenthesis is present on only the left or right end, the parenthesis will be
retained.

Examples
Let
string s1 = "(I don’t know)"

so that S1 contains the string “(I don’t know)”.

Then the commands


string sq1 = @stripparens("(I don’t know)")
string sq2 = @stripparens(s1)

create SQ1 and SQ2 which contain the string “I don’t know”.

If ALPHA1 is an alpha series, the command


alpha a1 = @stripquotes(alpha1)

fills A1 with parens-removed values of ALPHA1 for each observation in the workfile sample.

If AVEC1 is an svector, the commands


svector as1 = @stripparens(avec1)
svector as2 = @stripparens(avec1.@rows(@range(2, 6))

creates svectors AS1 and AS2, where AS1 contains parens-removed values of AVEC1, and
AS2 contains parens-removed values of the rows 2 through 6 of AVEC1.
@stripquotes—1131

Cross-references
See also @stripcommas (p. 1129) and @stripquotes (p. 1131).

@stripquotes Element Functions

Remove paired double-quotation marks surrounding string.


Syntax: @stripquotes(str)
str: string
Return: string

Returns the contents of the string str with double-quotation marks stripped from both the
left and the right ends with leading and trailing whitespace ignored. If a double-quote is
present on only the left or right end, the double-quote will be retained.

Examples
Let
string s1 = """Chicken Marsala"""

so that S1 contains the quoted string “"Chicken Marsala"”.

Then the commands


string sq1 = @stripquotes("""Chicken Marsala""")
string sq2 = @stripquotes(s1)

create SQ1 and SQ2 which contain the un-quoted string “Chicken Marsala”.

If ALPHA1 is an alpha series, the command


alpha a1 = @stripquotes(alpha1)

fills A1 with strip-quoted values of ALPHA1 for each observation in the workfile sample.

If AVEC1 is an svector, the commands


svector as1 = @stripquotes(avec1)
svector as2 = @stripquotes(avec1.@rows(@fill(1, 3, 5))

create svectors AS1 and AS2, where AS1 contains double-quoted values of AVEC1, and AS2
contains double-quoted values of the rows 1, 3, and 5 of AVEC1.

Cross-references
See also @addquotes (p. 715), @stripcommas (p. 1129), and @stripparens (p. 1130).
1132—Function Reference: S

@strlen Element Functions

Length of string.
Syntax: @strlen(str)
str: string
Return: integer

Returns the length of the string str.

Examples
Let
string s1 = "(I don’t know)"

so that S1 contains the string “(I don’t know)”.

Then the commands


@strlen("(I don’t know)")
@strlen(s1)

both return the scalar value 14.

If ALPHA1 is an alpha series, the command


series d1 = @strlen(alpha1)

fills D1 with lengths of the strings in ALPHA1 for each observation in the workfile sample.

If AVEC1 is an svector, the commands


vector vec1 = @strlen(avec1)

creates the vector VEC1 containing the lengths of the elements of AVEC1.

Cross-references
Equivalent to @length (p. 944).

@strnow

String representation of the current date and time.


Syntax: @strnow(fmt)
fmt: date format string
Return: string
@subextract—1133

Returns a string representation of the current date number (at the moment the function is
evaluated) using the date format string, fmt.

Date format syntax is outlined in “Date Formats” on page 106.

Exampless
The command
@strnow("DD/mm/yyyy")
@datestr(@now, "DD/mm/yyyy")

both return the dates string at the moment of evaluation in “DD/mm/yyyy” format.

Using intra-day formats,


@strnow("yyyy-MM-DD HH:mi:ss")
@datestr(@now, "yyyy-MM-DD HH:mi:ss")

both return the date string at the moment of evaluation in "yyyy-MM-DD HH:mi:ss" format.

Cross-references
See also @strdate (p. 1128) and @datestr (p. 824).

@subextract

Extract submatrix from matrix object.


Syntax: @subextract(m, n1, n2[, n3, n4])
m: matrix, vector, sym
n1: integer
n2: integer
n3: (optional) integer
n4: (optional) integer
Return: matrix

Returns a submatrix of a specified matrix, m.


• The required arguments n1 and n2 are the row and column of the upper left corner of
the region to be extracted.
• The optional arguments n3 and n4 provide the row and column of the lower right cor-
ner of the region to be extracted.
• If n3 or n4 are not provided, the corresponding element will be the last row or column
of the source matrix.
1134—Function Reference: S

Note that in some circumstances, you may find it easier to use the newer “.sub”, “.row”, and
“.col” object data member functions. See “Matrix Data Members” on page 556 and “Sym
Data Members” on page 992 in Object Reference and the examples below.

Examples
matrix m1 = @mnrnd(20, 5)
matrix m1a = @subextract(m1, 3, 2)

extracts the 18  4 matrix from the lower right corner of M1 starting at row 3 and column
2, while
matrix m1b = @subextract(m1, 1, 1, 5, 4)

extracts the upper left corner of M2 up through row 5 and column 4.


matrix m1c = @subextract(m1, 3, 2, 7, 3)

extracts the subtract from rows 3 to 7 and columns 2 to 3.

The commands
matrix m1d = @subextract(m1, 3, 1, 3)
rowvector v1d = @rowextract(m1, 3)

both extract row 3 from the matrix, while


matrix m1e = @subextract(m1, 1, 4, @rows(m1), 4)
vector v1e = @columnextract(m1, 4)

extract column 4.

For illustration purposes, we repeat the previous commands followed by data member func-
tions to perform equivalent extractions:
• lower corner extraction,
matrix m1a = @subextract(m1, 3, 2)
matrix m1a_1 = m1.@sub(@range(3, m1.@rows), @range(2, m1.@cols))
• upper corner extraction,
matrix m1b = @subextract(m1, 1, 1, 5, 4)
matrix m1b_1 = m1.@sub(@range(1, 5), @range(1, 4))
• arbitrary rectangle extraction
matrix m1c = @subextract(m1, 3, 2, 7, 4)
matrix m1c_1 = m1.@sub(@range(3, 7), @range(2, 4))
• row extraction as rowvector
matrix m1d = @subextract(m1, 3, 1, 3)
matrix m1d_1 = m1.@sub(3, @range(1, m1.@cols))
@sum—1135

rowvector v1d = @rowextract(m1, 3)


rowvector v1d_1 = @transpose(m1.@row(3))
• column extraction
matrix m1e = @subextract(m1, 1, 4, @rows(m1), 4)
matrix m1e_1 = m1.@sub(@range(1, @rows(m1)), 4)
vector v1e = @columnextract(m1, 4)
vector v1e_1 = m1.@col(4)

Cross-references
See the newer “Matrix Data Members” on page 556 and “Sym Data Members” on page 992
in Object Reference.

See also @columnextract (p. 762) and @rowextract (p. 1089).

@sum

Arithmetic sum.

Computes the sum of the elements of x.


Syntax: @sum(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number
T
y   xt
t1

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x is a series of length 5 whose elements are 1, 2, 3, 4, 5, then
= @sum(x)

returns 15.

Cross-references
See also @inner (p. 922), @prod (p. 1042), and @sumsq (p. 1136).
1136—Function Reference: S

@sumsby

Sum of observations in a series for each specified group.


Syntax: @sumsby(x, y[y1, y2, ... yn, s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Compute the sum of observations in x for group identifiers defined by distinct values of y.

EViews will use the current or specified workfile sample.

Examples
show @sumsby(x, g1, g2)

produces a linked series of by-group sums of observations in x, where members of the same
group have identical values for both g1 and g2.

Cross-references
See also @sumsqsby (p. 1137).

@sumsq

Arithmetic sum of squares.

Computes the sum of the squared elements of x.


Syntax: @sumsq(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x is a series of length 5 whose elements are 1, 2, 3, 4, 5, then
= @sumsq(x)

returns 55.
@svd—1137

Cross-references
See also @inner (p. 922), @prod (p. 1042), and @sum (p. 1135).

@sumsqsby

Sum of squared observations in a series for each specified group.


Syntax: @sumsqsby(x, y, [s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Compute the sum of squared observations in x for group identifiers defined by distinct val-
ues of y.

EViews will use the current or specified workfile sample.

Examples
show @sumsqsby(x, g1, g2)

produces a linked series of by-group sums of squares of observations in x, where members


of the same group have identical values for both g1 and g2.

Cross-references
See also @sumsby (p. 1136).

@svd

Singular value decomposition (economy) of matrix


Syntax: @svd(m1, v1, m2)
m1: matrix, sym
v1: vector W
m2: matrix, sym V
Return: matrix U

Performs an “economy” or “thin” singular value decomposition of the matrix m1, generating
truncated results when m1 is not square (exploiting the reduced maximum rank of a non-
square matrix).
1138—Function Reference: S

The matrix U is returned by the function, the vector v1 will be filled (resized if necessary)
with the singular values and the matrix m2 will be assigned (resized if necessary) the other
matrix, V , of the decomposition. The singular value decomposition satisfies:
m1  UWV
UU  VV  I
where W is a diagonal matrix with the singular values along the diagonal. Singular values
close to zero indicate that the matrix may not be of full rank. See the @rank (p. 1063) func-
tion for a related discussion.

Let r be the number of rows of m1 and s be the number of columns of m1 so that m1 has at
most t = min(r, s) distinct singular values. Then
• m2 will be s-by-t
• v1 will be t-by-1
• U will have dimensions r-by-t

Examples
matrix x = @mnrnd(5, 7)
vector w
matrix v
matrix u = @svd(x, w, v)

performs the thin SVD of the matrix X. U is 5  5 , W is a 5 element vector containing the
singular values, and V is a 7  5 matrix.

Alternately, if the rank is less than the number of rows,


matrix x = @mnrnd(7, 5)
matrix u = @svd(x, w, v)

U is 7  5 , W is a 5 element vector containing the singular values, and V is a 5  5 matrix.

The following demonstrate the properties of the decomposition:


sym i1 = @inner(u)
sym i2 = @inner(v)
matrix x1 = u * @makediagonal(w) * v.@t

where I1 and I2 and the identity matrix, and X1 is equal to X.

Cross-references
See also @svdfull (p. 1139), @cholesky (p. 743), @lu (p. 954), and @qr (p. 1055).
@svdfull—1139

@svdfull

Singular value decomposition (full) of matrix


Syntax: @svdfull(m1, m2, m3)
m1: matrix, sym
m2: matrix
m3: matrix, sym
Return: matrix

Performs a singular value decomposition of the matrix m1.

The matrix U is returned by the function, the matrix m2 will be assigned (resized if neces-
sary) the matrix W , and the matrix m3 will be assigned (resized if necessary) the other
matrix, V , of the decomposition. The singular value decomposition satisfies:
m1  UWV
UU  VV  I
where W is a diagonal matrix with the singular values along the diagonal. Singular values
close to zero indicate that the matrix may not be of full rank. See the @rank (p. 1063) func-
tion for a related discussion.

Examples
matrix x = @mnrnd(5, 7)
matrix w
matrix v
matrix u = @svdfull(x, w, v)

performs the full SVD of the matrix X. U is 5  5 , W is 5  5 diagonal matrix with singular
values on the diagonal, and V is 7  5 .

Alternately, if the rank is less than the number of rows,


matrix x = @mnrnd(7, 5)
matrix u = @svdfull(x, w, v)

then U is 7  7 , W is a 7  5 matrix with the singular values on the main diagonal and V is
a 5  5 matrix.

In both cases, the following demonstrate the properties of the decomposition:


sym i1 = @inner(u)
sym i2 = @inner(v)
matrix x1 = u * w * v.@t
1140—Function Reference: S

where I1 and I2 and the identity matrix, and X1 is equal to X.

Cross-references
See also @svd (p. 1137), @cholesky (p. 743), @lu (p. 954), and @qr (p. 1055).

@sweep

Sweep operator.

There are two syntaxes for @sweep, one for the symmetric, and the other for then non-sym-
metric operator.
Syntax: @sweep(s[, n])
s: sym
k: integer
k2: (optional) integer
Return: matrix

Returns the result of applying the symmetric sweep operator to symmetric matrix S at diago-
nal element k. If k2 is specified, sweeps on all diagonal elements between k and k2, inclu-
sive.
Syntax: @sweep(m, r, c)
m: matrix, sym
r: integer
c: integer
Return: matrix

Returns the result of applying the non-symmetric sweep operator to general matrix m at ele-
ment (r, c).

The sweep operator is an elementary matrix row operation with particularly useful proper-
ties when applied to uncorrected sum of squares and cross-products (USSCP) matrices.
Among these properties is the ability to calculate the coefficients for one or more regressions
over a common set of regressors.

Let B  SWEEP k  A  be an application of the symmetric sweep operator. Then,


B kk  – 1  A kk , B ik  A ik  A kk where i  k , B kj  A kj  A kk where j  k , and
A ik A kj
B ij  A ij – ----------------
-
A kk

where i  k and j  k .
@sweep—1141

Let B  SWEEP rc  A  be an application of the non-symmetric sweep operator. Then,


B rc  1  A rc , B ic  A ic  A rc where i  r , B rj  – A rj  A rc where j  c , and
A ic A rj
B ij  A ij – ----------------
-
A rc

where i  r and j  c .

Examples
As an example of using the sweep operator to replicate the results of OLS regression, sup-
pose we have series for one dependent variable, Y, and three regressors, X1, X2, X3.

We can organize the data into a group YX = [Y X1 X2 X3], form the USSCP matrix (YX)'YX,
and apply the sweep operator to the three diagonal elements associated with the regressors
(elements 2-4).

Each application of the sweep operator to a diagonal element effectively switches the role of
the associated variable from dependent to regressor.
workfile u 1000
series y = nrnd
series x1 = nrnd
series x2 = nrnd
series x3 = nrnd
group g y x1 x2 x3
sym usscp = @inner(g)
sym S = @sweep(usscp, 2, 4)

The resulting block matrix will have the form:

–1 –1
S   YY – YX  XX  XY  YX  XX 
–1 –1
 XX  XY –  XX 

This matrix contains all the information usually associated with the results of OLS regres-
sion, which we can extract.
vector beta = @subextract(S, 2, 1, 4, 1) ' Regressor coefficients
scalar SSR = S(1,1) ' Sum of squared residuals
sym invXtX = -@subextract(S, 2, 2)
vector se = @sqrt(SSR * @getmaindiagonal(invXtX) / (@obssmpl - 3))
' Coefficient standard errors

We could compare these results to those of a standard equation object for the same regres-
sion.
equation eq.ls(noconst) y x1 x2 x3
1142—Function Reference: S

It is also possible to conduct multiple regressions against a set of common regressors. Con-
sider a small example with two dependent variables, y1 and y2, and two regressors, x1 and
x2. We proceed as before, again applying the sweep operator to only the two diagonal ele-
ments associated with regressors (3-4).
series y1 = nrnd
series y2 = nrnd
group g1 y1 y2 x1 x2
sym usscp1 = @inner(g1)
sym S1 = @sweep(usscp1, 3, 4)
matrix beta1 = @subextract(S1, 3, 1, 4, 2)
vector SSR1 = @getmaindiagonal(@subextract(S1, 1, 1, 2, 2))
sym invXtX1 = -@subextract(S1, 3, 3)
vector se1 = @sqrt(@kronecker(SSR1, @getmaindiagonal(invXtX1)) /
(@obssmpl - 2))

Again, we could compare these results to those of standard equation objects.


equation eq1.ls(noconst) y1 x1 x2
equation eq2.ls(noconst) y2 x1 x2

Cross-references
Goodnight, James H. (1979). “A Tutorial on the SWEEP Operator,” The American Statisti-
cian, 33, 149–158.

See also @rsweep (p. 1097).


@tablenames—1143

Function Reference: T
@tablenames ........Tables names in a foreign file (p. 1143).
@tan ....................Tangent of argument specified in radians (p. 1144).
@tdist...................Tail probabilities of the Student’s t distribution (p. 1144).
@temppath ...........Directory path for EViews temporary files (p. 1145).
@theil...................Theil inequality coefficient (difference) between series (p. 1145).
@time...................Current time as a string (p. 1146).
@toc.....................Elapsed time (since timer reset) in seconds (p. 1146).
@trace ..................Computes the trace of a square matrix or sym (p. 1147).
@transpose ...........Transpose of a matrix object (p. 1147).
@trend .................Trend series (p. 1148).
@trendbr ..............Trend series with break (p. 1149).
@trendc................Trend series using calendar dates (p. 1150).
@trendcoef ...........Trend coefficient from detrending a series (p. 1151).
@trigamma...........Second derivative of the natural log gamma function (p. 1152).
@trim ...................Trim left and right whitespace from string (p. 1153).
@trmean...............Trimmed mean (p. 1154).
@tz ......................Convert time in source time zone to destination time (p. 1155).
@tzlist ..................Available time zone specifications (p. 1155).
@tzspec ................Time zone specification (p. 1156).

@tablenames

Table and sheet names in a foreign file.


Syntax: @tablenames("str")
str: string
Return: string

Returns a space delimited string containing the names of the table names of a foreign file.
The name (and path) of the foreign file should be specified in str, enclosed in quotes.

For an Excel file, the names of the Excel sheets will be returned.
1144—Function Reference: T

@tan Element Functions

Tangent of argument specified in radians.

Compute the tangent of x (specified in radians).


Syntax: @atan(x)
x: number
Return: number

Examples
= @tan((5/4)*@pi)

returns 1.

Cross-references
See also @acos (p. 714), @asin (p. 717), @atan (p. 718), @cos (p. 766), and @sin (p. 1112).

@tdist Element Functions

Tail probabilities of the Student’s t distribution.


Syntax: @tdist(x, v)
x: number
v: number, v  0
Return: number

Probability that a t-statistic with v degrees of freedom exceeds x in absolute value (two-sided
p-value).
–x 
Pr  X  x v   – f  s v  ds   f  s v  ds
x
–x
 2 f  s v  ds
–

due to symmetry, where


v1
G  ------------ v  1
–--------------------
 2  2
s  2
 
f  s v   --------------------------- 1  ----
--1-   v 
v
 vp  G  ---
2
 2

Examples
= @tdist(-12.71, 1)
@theil—1145

returns 0.04998....

Cross-references
See also @ctdist (p. 775), @dtdist (p. 847), @qtdist (p. 1056), and @rtdist (p. 1099).

@temppath

Directory path for the EViews temporary files.


Syntax: @temppath
Return: string

Returns a string containing the directory path for the EViews temporary files as specified in
the global options File Locations.... menu.

Examples
If your currently executing copy of EViews puts temporary files in “D:\EVIEWS”, then:
%y = @temppath

assigns a string of the form “D:\EVIEWS”.

Cross-references
See also @evpath (p. 878) and @addinspath (p. 714).

@theil

Theil inequality coefficient (difference) between series.

Computes the Theil inequality coefficient of x and y.


Syntax: @theil(x, y, [s])
x: series
y: series
s: (optional) sample string or object
Return: number

The Theil inequality coefficient is given by the root mean square error divided by the sum of
the square roots of the squared x and squared y means).
1146—Function Reference: T

T
1 2
----   x t – y t 
T
t1
z t  ----------------------------------------------------------
-
T T
1 2 1 2
----  x t  ----  y t
T T
t1 t1

Examples
Let yf denote in-sample forecasts for the series y. Then
= @theil(yf, y)

returns the Theil inequality coefficient between the series y and its forecast.

Cross-references
See also @rmse (p. 1084).

@time

Current time as a string.


Syntax: @time
Return: string

Returns a string containing the current time in “hh:mm” format.

Examples
%y = @time

assigns a string of the form “15:35”.

Cross-references
See also @date (p. 814) and @now (p. 1013).

@toc

Elapsed time (since timer reset) in seconds


Syntax: @toc
Return: integer

Compute elapsed time (since timer reset) in seconds.

Examples
tic
@transpose—1147

[some commands]
!elapsed = @toc

resets the timer, executes commands, and saves the elapsed time in the control variable
!ELAPSED.

Cross-references
See also tic (p. 611) and toc (p. 611).

@trace

Computes the trace of a square matrix or sym.


Syntax: @trace(m)
m: matrix, sym
Return: scalar

Returns the trace (the sum of the diagonal elements) of a square matrix or sym, m.

Examples
matrix m1 = @mnrnd(10, 10)
scalar sc1 = @trace(m1)
scalar sc2 = @sum(@getmaindiagonal(m1))

generate a random matrix, and then compute the trace directly and indirectly.

Similarly,
matrix s1 = @inner(@mnrnd(100, 20))
scalar sc1a = @trace(s1)
scalar sc2a = @sum(@getmaindiagonal(s1))

generate a random sym, and then compute the trace in two ways.

Cross-references
See also @det (p. 835) and @eigenvalues (p. 864).

@transpose

Transpose of a matrix object.


Syntax: @transpose(m)
m: matrix, vector, rowvector, sym
Return: matrix, rowvector, vector, sym
1148—Function Reference: T

The result is a matrix object with the number of rows and columns and the element indices
reversed from the original matrix. This function is an identity function for a sym, since a
sym by definition is equal to its transpose.

Examples
matrix m1 = @mnrnd(5, 7)
matrix m1t = @transpose(m1)

creates a 5  7 matrix M1 filled with normal random variables, and the 7  5 matrix trans-
pose.
vector v1 = @mnrnd(10)
matrix m2 = v1 * @transpose(v1)
matrix m3 = @outer(v1, v1)

creates the 10-element vector V1 and forms its 10  10 outer product matrix in two ways.

Note that the transpose of matrix objects may also be obtained using the “@t” object data
member function, as in
matrix m4 = v1 * v1.@t

Cross-references
See “Matrix Data Members” on page 556, “Vector Data Members” on page 1223, and “Sym
Data Members” on page 992 in Object Reference.

@trend

Trend.
Syntax: @trend([d])
d: (optional) date or observation
Return: series

Returns a time trend that increases by one for each observation in the workfile.

The optional date or observation d may be provided to indicate the starting point (with a 0
value) for the trend. If d omitted, the starting point is assumed to be the earliest date in the
workfile.

This function is panel aware. In this context, trend values are defined sequentially across the
entire set of available cross-section dates, and then matched to the individual cross-section
dates. If there is a specific date that is missing in one cross-section, but is present in another,
there will be a gap (non-sequential values) in the trend in the former. Thus, the panel trend
may be thought of as a calendar trend that uses the calendar defined by dates observed in
the workfile.
@trendbr—1149

For a trend function that uses calendar dates, use @trendc (p. 1150). For a simple panel
trend in which values begin at 1 and sequentially increase by 1, you may use the @obsid
(p. 1016) function.

Examples
series t = @trend

creates a trend series starting at 0 in the first workfile observation.


series t90q1 = @trend("1990q1")

creates a trend series based at 0 in 1990q1.

Cross-references
See also @trendbr (p. 1149) and @trendc (p. 1150).

@trendbr

Trend with break.


Syntax: @trendbr([d])
d: (optional) date or observation
Return: series

Returns a breaking time trend that is zero for each observation prior to and at the break
point, and increases by one for each observation following the break.

The optional date or observation d may be provided to indicate the break/starting point for
the trend. If d omitted, the break point is assumed to be the first observation, and the func-
tion produces a simple trend.

This function is panel aware. In this context, trend values are defined sequentially across the
entire set of available cross-section dates, and then matched to the individual cross-section
dates. If there is a specific date that is missing in one cross-section, but is present in another,
there will be a gap (non-sequential values) in the trend in the former. Thus, the panel trend
may be thought of as a calendar trend that uses the calendar defined by dates observed in
the workfile.

To obtain a simple panel trend in which values begin at 1 and sequentially increase by 1,
you may use the @obsid (p. 1016) function.

Examples
series tbr90q1 = @trendbr("1990q1")

creates a trend series based at 0 in 1990q1. Observations before 1990q1 will be set to 0;
observations after 1990q1 will sequentially increase by 1.
1150—Function Reference: T

Cross-references
See also @obsid (p. 1016), @trend (p. 1148) and @trendc (p. 1150).

@trendc

Calendar trend.
Syntax: @trendc([d])
d: (optional) date or observation
Return: series

Returns a calendar time trend that increases by the number of calendar periods between suc-
cessive observations.

The optional date or observation d may be provided to indicate the starting point (with a 0
value) for the trend. If d omitted, the starting point is assumed to be the earliest observation
in the workfile.
• In a regular frequency workfile, @trend and @trendc both return a simple trend that
increases by one for each observation of the workfile.
• In an irregular workfile, @trend provides an observation-based trend as before, but
@trendc now returns a calendar trend that increases based on the number of calen-
dar periods between adjacent observations. For example, in a daily irregular file
where a Thursday has been omitted because it was a holiday, the @trendc value
would increase by two between the Wednesday before and the Friday after the holi-
day, while @trend will increase by only one.

This function is panel aware. For a panel trend function that uses only the observed dates,
use @trend (p. 1148). For a simple panel trend in which values begin at 1 and sequentially
increase by 1, you may use the @obsid (p. 1016) function.

Examples
series t = @trend

creates a calendar trend series starting at 0 in the first workfile observation.


series t90q1 = @trend("1990q1")

creates a calendar trend series based at 0 in 1990q1.


@trendcoef—1151

Cross-references
See also @trend (p. 1148), @trendbr (p. 1149), and @obsid (p. 1016).

@trendcoef

Trend coefficient from detrending regression.

Computes the trend coefficient (or coefficients for panel data) of an OLS regression versus a
constant and an implicit time trend.
Syntax: @trendcoef(x[, s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to
series
Return: number

Returns the trend coefficient of an OLS regression on matrix or vector m versus a constant
and an implicit time trend, as in @detrend.

When applied to a matrix, the matrix elements are arranged in vectorization order and then
paired with the implicit time trend.

This function is panel aware.

For series calculations, EViews will use the current or specified workfile sample.

Examples
series y = 2 + 3 * @trend + @nrnd
= @trendcoef(y)

The first line generates the series y using a simple linear regression model, where the sole
regressor is a time trend, the intercept is 2, and the slope coefficient is 3. The second line
returns the OLS estimate of the slope coefficient, and is approximately 3 in large samples.

The following commands begin by creating a workfile, generating a random series, and then
converting to a vector so that we can compute identical results using the series and the vec-
tor.
workfile u 100
series y = nrnd
vector yv = @convert(y)

The trend regression trend coefficient estimate is given by


scalar tr1 = @trendcoef(yv)
1152—Function Reference: T

Alternately, the trend regression results may be obtained using the vector YV using the
@regress command on the augmented data matrix:
matrix vcoefs = @regress(@hcat(yv, @ones(yv.@rows), @range(0,
yv.@rows-1)))

The first column of VCOEFS contains the intercept and trend coefficient, so
scalar tr2 = vcoefs(2)

is the trend coefficient.

Estimates may also be obtained using the series and an equation object
equation eq1.ls y c @trend
scalar tr3 = eq1.c(2)

Cross-references
See also @cintercept (p. 747), @ctrendcoef (p. 775), and @intercept (p. 925).

@trigamma Element Functions

Second derivative of the natural log gamma function.


Syntax: @trigamma(x)
x: number
Return: number
2
d log G  x 
w  x   --------------------------
2
dx
for x  0 .

Examples
= @trigamma(0.5)

returns 4.93480... (equivalent to 0.5p 2 ).


@trim—1153

Cross-references
See also @gammalog (p. 894) and @digamma (p. 839).

@trim Element Functions

Trim left and right whitespace from string.


Syntax: @trim(str)
str: string, alpha, svector
Return: string, alpha, svector

Returns the string str with spaces trimmed from the left and the right.

Examples
@ltrim(" I doubt that I did it. ")

returns “I doubt that I did it.” after trimming off spaces from both ends.

If ALPHA1 is an alpha series,


alpha alphaltrim = @trim(alpha1)

returns the left and right-trimmed strings in ALPHA1 for each observation in the workfile
sample.

If SVEC1 is an string vector,


svector sveclen = @trim(svec1)

returns a string vector containing the left and right-trimmed elements of SVEC1.

Cross-references
See also @ltrim (p. 953) and @rtrim (p. 1100).
1154—Function Reference: T

@trmean

Trimmed mean.

Compute the mean after the p-percent largest and smallest values have been removed.
Syntax: @trmean(x, p[, s])
x: series, vector, matrix
p: number, series, vector, matrix
s: (optional) sample string or object when x is a series and assigning to a
series
Return: number

For x with T observations and 0  p  50 , define the number of trimmed end observations
as k   pT   100 , where z is the integer floor function.

Then the trimmed mean is given by


T–k
1
y   -----------------   xt
 T – 2k 
tk

where the order statistics  x  1 , x  2 , , x  T   represent data for the T observations


ordered from low to high,

For series calculations, EViews will use the current or specified workfile sample.

Examples
= @trmean(y, 5)

computes the 5% trimmed mean for series y.

Consider the commands


matrix m = @mrnd(10,10)
m(1,1) = 1000
scalar om = @mean(m)
scalar trm = @trmean(m,1)

The mean of M should be approximately 10.495, whereas the trimmed mean (with the larg-
est and smallest 1% trimmed off) should be close to 0.5.

Cross-references
See also @mean (p. 971).
@tzlist—1155

@tz

Convert time in source time zone to destination time.


Syntax: @tz((srctime, srctzone, destzone)
srctime: date number
srctzone: string
destzone: string
Return: date number

Converts a point in time srctime from the source time zone srctzone into the corresponding
time in the destination time zone destzone.
• The srctzone and destzone strings can either contain raw time zone information in the
format returned by @tzspec (p. 1156) or they can contain search text (such as a city
name) found within one of the time zone descriptions returned by the function
@tzlist (p. 1155).

Examples
series localtime = @tz(utctime, "London", "Sydney")

converts a series containing time values in London local time into equivalent local time val-
ues in Sydney.

Cross-references
See “Dates,” on page 104 and “Event Functions,” on page 311 for related discussion.

See also the related time zone functions @utc (p. 1173), @localt (p. 946), @tzlist
(p. 1155), and @tzspec (p. 1156).

@tzlist

Available time zone specifications.


Syntax: @tzlist
Return: string

Returns a space delimited list of descriptions of all the time zones for which information is
available on the current machine.

Examples
string all_specs = @tzlist
1156—Function Reference: T

saves the list of all available time zone specifications for the current machine to the string
object ALL_SPECS.

Cross-references
See “Strings,” on page 85 and “Event Functions,” on page 311 for related discussion.

See also the related time zone functions @utc (p. 1173), @localt (p. 946), @tz (p. 1155),
and @tzspec (p. 1156).

@tzspec

Time zone specification.


Syntax: @tzspec(str)
str: string
Return: string

Returns time zone information for the first time zone whose description contains the piece
of text passed in as str.

tr can be a city name such as “London” or “Tokyo” or any other word from the time zone
description such as “Eastern” for the U.S. Eastern Time Zone.

Time zone information specifications have the format:


standard_utc_bias [daylight_offset daylight_start_rule daylight_end_rule]

where:
• standard_utc_bias is the offset (in +/– hh:mi format) of local time from UTC when
daylight time is not in effect.
• daylight_offset is the additional adjustment (in +/– hi:mi format) to the standard UTC
bias when daylight time is in effect.
• daylight_start_rule is the day/time when the daylight time adjustment begins. This
can be an explicit date or a date rule.
• daylight_end_rule is the day/time when the daylight time adjustment ends. This can
be an explicit date or a date rule.

If there have been historical changes to the time zone rule, each era is returned beginning
with an “@” symbol followed by the year in which the new rule took effect. The year may
be dropped to indicate that the rule should be applied to all earlier dates.

For example, a historical description of the Pacific Time Zone (PT) description for parts of
western Canada, the western United States, and western Mexico (valid from 1987 onwards)
has the specification:
@tzspec—1157

@2007 -08:00 +01:00 Mar2Sun 2AM to Nov1Sun 2AM


@ -08:00 +01:00 Apr1Sun 2AM to Oct-1Sun 2AM

The standard offset of the Pacific Time Zone from UTC is -8 hours. The daylight rule after
2007 has been to move clocks forward by one hour at 2AM on the second Sunday of March
and move them back at 2AM on the first Sunday in November. Before 2007 the rule was to
move clocks forward by one hour at 2AM on the first Sunday of April, and move them back
at 2AM on the last Sunday in October.

Examples
The command
string london_spec = @tzspec("London")

assigns a text description of the London time zone specification (Greenwich Mean Time
(GMT) during standard time and British Summer Time (BST) during Daylight Saving Time
(DST)),
+00:00 +01:00 Mar-1Sun 1:00 to Oct-1Sun 2:00

to the string object LONDON_SPEC, while


string eastern_spec = @tzspec("Eastern")

assigns the U.S. Eastern Time Zone (ET) description


@2007 -05:00 +01:00 Mar2Sun 2:00 to Nov1Sun 2:00 @ -05:00 +01:00
Apr1Sun 2:00 to Oct-1Sun 2:00

to the string object EASTERN_SPEC.

If ALPHA1 is an alpha series, the command


alpha a1 = @tzspec(alpha1)

fills A1 with time-zone specifications associated with the spec in ALPHA1, for each observa-
tion in the workfile sample.

If AVEC1 is an svector, the commands


svector s1 = @tzspec(avec1)

creates a vector of time-zone specifications corresponding to elements of AVEC1.

Cross-references
See “Dates,” on page 104 and “Event Functions,” on page 311 for related discussion.

See also the related time zone functions @utc (p. 1173), @localt (p. 946), @tz (p. 1155),
and @tzlist (p. 1155).
1158—Function Reference: T
@uidialog—1159

Function Reference: U
@uidialog .............Display a dialog with multiple controls (p. 1159).
@uiedit.................Display a dialog with an edit control (p. 1162).
@uifiledlg .............Display a file open and save dialog (p. 1163).
@uilist..................Display a dialog with a listbox control (p. 1164).
@uimlist...............Display a dialog with a multiple-select listbox control (p. 1165).
@uiprompt ...........Display a prompt dialog (p. 1166).
@uiradio...............Display a dialog with radio buttons (p. 1168).
@uniquevals.........Vector or svector of unique values of object (p. 1169).
@unitvector ..........Extracts column from an identity matrix (p. 1169).
@unvec ................Unstack vector into a matrix (p. 1170).
@unvech ..............Unstack vector into lower triangle of sym (p. 1171).
@upper.................Uppercase representation of a string; or upper triangular matrix of a
matrix (p. 1171).
@utc.....................Convert local time to UTC (Coordinated Universal Time) (p. 1173).

@uidialog

Display user dialog with multiple controls.


Syntax: @uidialog(spec1[, spec1, [spec3, [...])
spec#: string
Return: integer

Displays a dialog with any number of controls that you define, including edit fields, list-
boxes, radio buttons, checkboxes, text, and captions. You may specify an combination of
controls, and they will be arranged in the order they are entered. EViews attempts to lay the
controls out in a visually pleasing manner, and will do its best to size and arrange the dialog
accordingly.

Each cinfo# item is a specification of the control type in quotes (“Edit”), followed by appro-
priate parameters. You may specify any combination of controls, where each should follow
one of the following forms:
Edit field “Edit”, IO_String, prompt_string[, max_edit_length]
Listbox “List”, IO_StringOrScalar, prompt_string, list_string
Radio buttons “Radio”, IO_Scalar, prompt_string, list_string
Checkbox “Check”, IO_Scalar, prompt_string
Text “Text”, text_string
1160—Function Reference: U

Caption “Caption”, caption_string


Column break “Colbreak”
OK Button “Button”, button_string
Cancel Button “Buttonc”, button_string

In the above table, the parameters can be described as:


IO_String string used to initialize an edit field and hold the final edit
field text.
IO_Scalar scalar used to initialize a radio or checkbox selection, and
hold the final selection.
IO_StringOrScalar string or scalar used to initialize a listbox selection, and
hold the final selection.
prompt_string string used as the label for the control, or the groupbox
label for radio buttons.
max_edit_length scalar for the maximum characters allowed in an edit field.
list_string space delimited list of entries for a listbox or radio buttons.
text_string text to be used in a text control.
caption_string text to be used as the caption of the dialog in its titlebar.
button_string text to be used on the button.

Note that parameters whose names begin with “IO_”, e.g. “IO_String” should be passed into
the function using replacment variables or objects in the workfile, as they are used to return
results.

The “button” and “buttonc” controls add a custom button to the dialog. The dialog will
close after a button has been pressed. The behavior of the button will depend on the type of
button —buttons of type “button” will behave in the same way as the “OK” button (i.e., all
variables passed into the dialog will be updated to reflect changes made to their correspond-
ing controls). Buttons of type “buttonc” will behave in the same way as the “Cancel” button
(i.e., all variables will be reset to the values that were passed into the dialog).

The return value of the dialog will correspond to the order in which buttons are placed in
the dialog. If only one button (apart from the standard “OK” and “Cancel”) is included in
the dialog, the return value for that button will be “1”. If there is more than one button, then
the first button will return a value of “1”, the second will return a value of “2” and so on.
Note that the return value is independent of whether the button was of type “button” or
“buttonc”. The specification for the button controls is (“button[c]”, “text”) where text speci-
fies the text that will be on the button.
@uidialog—1161

Examples
scalar dinner = 2
string dinnerPrompt = "Choose dinner"
string menu = """Chicken Marsala"" ""Beef Stew"" Hamburger Salad"
string name
string namePrompt = "Enter your name"
scalar result = @uidialog("Caption", "Dinner Menu", "Edit", name,
namePrompt, 64, "Radio", dinner, dinnerPrompt, menu)

These commands display a dialog with an edit field and


four radio buttons labeled “Chicken Marsala”, “Beef
Stew”, “Hamburger”, and “Salad”. The title “Enter your
name” appears above the edit field, while the groupbox
surrounding the radio buttons is labeled “Choose din-
ner”. The words “Dinner Menu” appear in the caption
area, or titlebar, of the dialog. The edit field is initially
blank, since we did not assign any text to the string
NAME. The dinner selection radio buttons are initialized
with the value 2, so the “Beef Stew” radio will be
selected. We limit the name length to 64 characters.
string introString = "We have many
pieces to suit your style."
string clothesList = "Shirt Pants Shoes Hat Tie"
string listTitle = "Please make a selection"
scalar selection = 3
@uidialog("text", introString, "list", selection, listTitle,
clothesList)

This creates a dialog with a text string and a listbox. The


text “We have many pieces to suit your style” appears at the
top. A listbox follows, with the label “Please make a selec-
tion” and the options: “Shirt”, “Pants”, “Shoes”, “Hat”, and
“Tie”. The listbox is initialized to the third item, “Shoes”. If
the user then selects the first item, “Shirt”, from the listbox
and presses OK, the scalar SELECTION will hold the value
1.

Note that the text control can be used to help achieve the
layout you desire. You can use it to insert empty text strings
to add space between adjacent controls. For example,
scalar a = 1
1162—Function Reference: U

scalar b = 0
@uidialog("check", a, "Option 1", "text", "", "check", b, "Option
2")

will leave a space between the two checkboxes. In more complicated dialogs, this may also
push the latter controls to a second column. You may have to experiment with the appear-
ance of more complex dialogs.

Cross-references
See “User-Defined Dialogs” on page 178 for additional discussion.

For a detailed description of each control type, see @uiedit (p. 1162), @uilist (p. 1164),
@uiprompt (p. 1166), @uiradio (p. 1168).

@uiedit

Displays a dialog with an edit field.


Syntax: @uiedit(arg, prompt[, maxlen])
input: string object, replacement variable
prompt: string
maxlen: (optional) integer
Return: integer

Displays a dialog with an edit field and prompt string that will be used to label the edit field.
• arg is generally entered as a replacement variable or an object in your workfile as it is
used to return results. arg is used to initialize the edit field and will contain the value
after editing.
• prompt may be specified using in-line text.
• maxlen is an optional maximum character length of the edit field. The default maxi-
mum length is 32 characters.

The dialog shows an OK and Cancel button, and will return an integer representing the but-
ton clicked: Cancel (-1), OK (0).

Examples
string name = "Joseph"
@uiedit(name, "Please enter your First Name:")

These commands display a dialog with the text “Please enter your First Name:” followed by
an edit field, initialized with the string “Joseph”. If the user edits the string to read “Joe” and
@uifiledlg—1163

presses the OK button, the dialog returns a value of 0 and NAME will now contain the
string: Joe.

Similarly,
@uiedit("", "Please enter your age:", 2)

brings up a dialog with the prompt “Please enter your age” and an empty edit field with a
maximum length of two characters. The user will not be able to enter more than two charac-
ters into the edit field.

Cross-references
See “User-Defined Dialogs” on page 178 for discussion.

See also @uidialog (p. 1159), @uilist (p. 1164), @uiprompt (p. 1166), @uiradio
(p. 1168).

@uifiledlg

Displays a standard Windows file open or save dialog


Syntax: @uifiledlg(input, filter, type)
input: string object, replacement variable
filter: string
type: string
Return: integer

Displays a file open/save style dialog.


• input should be either a replacement variable or a string object in your workfile as it
is used to return results. input is used to provide an initial location and possibly a
name of the file, and will contain the dialog specified value on return.
• filter specifies the name extensions of variables to show, with, for example, “” used to
denote all files, and “prg” used to limit the display to files ending in “.prg”
• type determines whether the shown dialog has an “open” or a “save” title.

Both filter and type may be specified using in-line text.

Note that the clicking OK on the dialog does not actually open or save the selected file, it
merely returns the name of the selected file. Thus, specifying the type argument is simply
cosmetic.)

The displayed dialog will display both an OK and a Cancel button, and will return an inte-
ger representing the button clicked: Cancel (-1), OK (0).
1164—Function Reference: U

Examples
string myfile = "c:\temp\"
@uifiledlg(myfile, "prg", "open")

These commands display a file open dialog style containing a list of all files with a “.prg”
extension in the folder “c:\temp\”. The user can navigate through the file system and select
another file, whose path and name will be returned in the string MYFILE.

Note that the slightly different set of commands


string myfile = "c:\temp"
@uifiledlg(myfile, "prg", "save")

will instead display a save dialog that opens in the “c:\” folder with the filename initialized
to “temp.prg” (since MYFILE does not have the trailing “\”).

Leaving the filename argument blank on input will open the dialog in the default EViews
directory:
string myfile = ""
@uifiledlg(myfile, "", "save")

opens a save dialog in the default EViews directory with no filtering and no default file.

Cross-references
See “User-Defined Dialogs” on page 178 for discussion.

See also @uidialog (p. 1159), @uiedit (p. 1162), @uilist (p. 1164), @uiprompt
(p. 1166), @uiradio (p. 1168).

@uilist

Displays a dialog with a listbox.


Syntax: @uilist(arg, prompt, items)
arg: scalar, program variable, string, replacement variable
prompt: string
items: string
Return: integer

Displays a dialog with a listbox and prompt string that will be used to label the listbox.
• arg should be an object or program variable as it is used to return results. arg is used
to provide an initial selection, and will contain the dialog specified value on return.
• prompt specifies the text used to label the listbox.
@uimlist—1165

• items is a space delimited list of items in the listbox.

Both prompt and items may be specified using in-line text.

The dialog shows an OK and Cancel button, and will return an integer representing the but-
ton clicked: Cancel (-1), OK (0).

Examples
string selection = "Item2"
@uilist(selection, "Please select an item:", "Item1 Item2 Item3")

These commands display a dialog with a listbox containing the items “Item1”, “Item2”, and
“Item3”. The title “Please select an item:” appears above the listbox, and the second item is
initially selected. If the user selects the third item and presses OK, the string SELECTION
will contain “Item3”, and the dialog will return the value 0.

Similarly,
scalar sel = 3
@uilist(sel, "Please select an item:", "Item1 Item2 Item3")

brings up the same dialog with the third item selected. The scalar SEL will contain the user’s
selection if OK is pressed.

Cross-references
See “User-Defined Dialogs” on page 178 for discussion.

See also @uimlist (p. 1165), @uidialog (p. 1159), @uiedit (p. 1162), @uiprompt
(p. 1166), @uiradio (p. 1168).

@uimlist

Displays a dialog with a multiple-selection listbox.


Syntax: @uimlist(arg, prompt, items)
arg: vector
prompt: string
items: string
Return: integer

Displays a dialog with a listbox and prompt string that will be used to label the listbox.
• arg should be an vector object as it is used to return results. arg is used to provide ini-
tial selections, and will contain the dialog specified values on return. On intialization
and return arg should contain the index values of the items in the listbox that are
1166—Function Reference: U

selected. If no items are selected arg will be a one element vector containing the value
-1.
• prompt specifies the text used to label the listbox.
• items is a space delimited list of items in the listbox.

Both prompt and items may be specified using in-line text.

The dialog shows an OK and Cancel button, and will return an integer representing the but-
ton clicked: Cancel (-1), OK (0).

Examples
vector(2) selected
selected.fill 1,3
@uimlist(selected, "Please select an item:", "Item1 Item2 Item3")

These commands display a dialog with a multiple listbox containing the items “Item1”,
“Item2”, and “Item3”. The title “Please select an item:” appears above the listbox, and the
first and third items are initially selected. If the user additionally selects the second item and
presses OK, the vector SELECTED will contain the elements 1,2,3, and the dialog will return
the value 0.
@uimlist(selected, "Please select an item:", "Item1 Item2 Item3")

If no items are selected in the dialog, SELECTED will be a one element vector containing the
value -1.

Cross-references
See “User-Defined Dialogs” on page 178 for discussion.

See also @uilist (p. 1164), @uidialog (p. 1159), @uiedit (p. 1162), @uiprompt
(p. 1166), @uiradio (p. 1168).

@uiprompt

Display prompt dialog.


Syntax: @uiprompt(msg[, button, beep])
msg: string
button: string
beep: string
Return: integer
@uiprompt—1167

Displays a prompt dialog with OK, Cancel, or Yes and No buttons. You must specify a mes-
sage string for the prompt dialog, and optionally the type of icon and buttons the dialog
should display. You may also instruct the message box to issue a beep when displayed.

The dialog will return an integer representing the button clicked: Cancel (-1), OK (0), Yes
(1), or No (2).

button_type can be one of the following keywords:


“O” Exclamation icon with OK button (default).
“OC” Exclamation icon with OK and Cancel buttons.
“YN” Question icon with Yes and No buttons.
“YNC” Question icon with Yes, No, and Cancel buttons.

beep_type can be one of the following keywords. The keywords change the type of beep that
is omitted, where those beeps are defined by the Windows operating system definitions. If
beep_type is omitted, no beep will be issued.
“B” Base type of beep on button_type
“AB” Asterisk beep
“CB” Critical stop / error beep
“QB” Question beep
“EB” Exclamation beep
“DB” Default beep

Examples
@uiprompt("Error: Too many observations")

Displays a dialog with the message “Error: Too many observations” and the OK button.
@uiprompt("Exceeded count. Would you like to continue?", "YNC")

Displays a dialog with the error message “Exceeded count. Would you like to continue?” and
the YES, NO, and CANCEL buttons. If the user presses the YES button, the dialog will return
the value 1.

Cross-references
See “User-Defined Dialogs” on page 178 for discussion.

See also @uidialog (p. 1159), @uilist (p. 1164), @uiedit (p. 1162), @uiradio (p. 1168).
1168—Function Reference: U

@uiradio

Displays a dialog with radio buttons.


Syntax: @uiradio(arg, prompt, items)
arg: scalar, program variable
prompt: string
items: string
Return: integer

Displays a dialog with a listbox and prompt string that will be used to label the listbox.
• arg should be an scalar or program variable as it is used to return results. arg is used
to provide initial selections, and will contain the dialog specified values on return.
• prompt specifies the text used to label the listbox.
• items is a space delimited list of items in the listbox.

Both prompt and items may be specified using in-line text.

The dialog shows an OK and Cancel button, and will return an integer representing the but-
ton clicked: Cancel (-1), OK (0).

Examples
scalar selection = 2
@uiradio(selection, "Please select an item:", "Item1 Item2 Item3")

These commands display a dialog with three radio buttons, labeled “Item1”, “Item2”, and
“Item3”. The title “Please select an item:” appears above the radio buttons, and the second
item is initially selected. If the user selects the third item and presses OK, the scalar SELEC-
TION will contain the value 3, and the dialog will return the value 0.

Cross-references
See “User-Defined Dialogs” on page 178 for discussion.

See also @uidialog (p. 1159), @uilist (p. 1164), @uiprompt (p. 1166), @uiedit
(p. 1162).
@unitvector—1169

@uniquevals

Vector or svector of unique values of object.


Syntax: @uniquevals(o)
o: series, matrix, vector, alpha
Return: vector, svector

Returns a vector or svector containing the list of unique values in the object specified by arg.
• If arg is a series, vector or matrix, @uniquevals will return a vector object containing
the unique elements of the series, vector or matrix.
• If arg is an alpha series, @uniquevals will return an svector of the unique values in
the alpha.

Examples
vector vals = @uniquevals(x)

returns a vector containing the unique values in x.


vector ivals = @sort(@uniquevals(x))

returns a vector of the unique values of X, sorted from low to high.

Cross-references
See also @dupselem (p. 851), @dupsobs (p. 853), and @dupsid (p. 852).

@unitvector

Extracts column from an identity matrix.


Syntax: @unitvector(n1, n2)
n1: integer
n2: integer
Return: vector

Creates an n1 element vector with a 1 in the n2-th element, and 0 elsewhere.

Examples
vector v1 = @unitvector(8, 5)

creates an 8 element vector with a 1 in the fifth element and 0 for the other 7 elements.
vector v2 = @unitvector(8, 3)
matrix h = @mnrnd(8, 8)
1170—Function Reference: U

matrix hselect1 = h * v2
matrix hselect2 = h.@col(3)

create HSELECT1 and HSELECT2 into which we extract column 3 from the matrix H.

Cross-references
See also @identity (p. 913), @ones (p. 1018), and @zeros (p. 1225).

@unvec

Unstack vector into a matrix.


Syntax: @unvec(v, n)
v: vector
n: integer
Return: matrix

Creates an n-row matrix filled with the unstacked elements of the vector v. EViews will
report a size mismatch if the number of elements of v is not evenly divisible by n.

Note that @unvec is the inverse of the @vec function.

Examples
vector v1 = @mrnd(12)

creates a 12 element vector of uniform random numbers V1 and unstacks it into a 3  4


matrix M1.
matrix m2 = @mnrnd(12, 3)
matrix m3 = @unvec(@vec(m2), 6)

generates a 12  3 matrix of random normals M2, then reshapes the matrix into a 6  6
matrix M3.

Cross-references
See also @unvech (p. 1171), @vec (p. 1183), and @vech (p. 1184).
@upper—1171

@unvech

Unstack vector into lower triangle of sym.


Syntax: @unvech(v)
v: vector
Return: sym

Creates a sym matrix with lower triangle filled using the unstacked elements of the vector v.
The sym will be sized automatically. EViews will report a size mismatch if the number of
elements of v does not correspond to a valid sym matrix size (is not a triangular number).

Note that @unvech is the inverse of the @vech function.

Examples
vector v1 = @mnrnd(15)
sym s1 = @unvech(v1)

creates a 15-element vector of normal random numbers V1 and unstacks it into a 5  5 sym
matrix S1.

Cross-references
See also @unvec (p. 1170), @vec (p. 1183), and @vech (p. 1184).

@upper Element Functions | String Functions | Matrix Utility

Uppercase representation of string or upper triangular matrix of a matrix.


String
Syntax: @upper(str)
str: string
Return: string

Returns the uppercase representation of the string str.


Matrix
Syntax: @upper(x[, n])
x: matrix, sym
n (optional) integer
Return: matrix

Returns a matrix whose elements on and above the n-th diagonal match the corresponding
elements of the matrix m, but whose elements below the n-th diagonal are zero.
1172—Function Reference: U

By default, n is has a value of zero indicating the main diagonal. Positive values of n indi-
cate super-diagonals, while negative values of k indicate sub-diagonals.

Examples
String
If we define the string object
string s1 = "I did NOT do it"

the commands
@upper("I did NOT do it")
@upper(s1)

return the string “I DID NOT DO IT”.

If ALPHA1 is an alpha series,


alpha alphalwr = @upper(alpha1)

returns the upper of the strings in ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


svector sveclen = @upper(svec1)

returns a string vector containing the uppercased elements of SVEC1.


Matrix
The commands
matrix(3,3) m1
m1.fill 1, 2, 3, 4, 5, 6, 7, 8, 9
matrix u1 = @upper(m1)
matrix u2 = @upper(m1, 1)
matrix u3 = @upper(m1, -1)

create a 3  3 matrix M1 holding the values

1 4 7
2 5 8
3 6 9

while the matrix U1 contains,

1 4 7
0 5 8
0 0 9
@utc—1173

the matrix U2 contains,

0 4 7
0 0 8
0 0 0

and the matrix U3 contains,

1 4 7
2 5 8
0 6 9

If we have the commands,


sym s = @rwish(@identity(5), 5)
matrix s1 = @upper(s)
matrix s2 = @upper(s, 1)
matrix s2 = @upper(s, 1)

then S is a 5  5 sym matrix and S1 is a 5  5 upper triangular matrix with elements at or


above the main diagonal equal to those in S, and elements below the main diagonal equal to
zero. S2 is a strictly upper triangular matrix that is equal to S1, but with the main diagonal
elements also set to 0.

Cross-references
See also @lower (p. 951).

@utc

Convert local time to UTC (Coordinated Universal Time).


Syntax: @utc(localtime[, timezone])
localtime: date number, series, vector
timezone: (optional) string, alpha, svector
Return: date number, series, vector

Returns the Coordinated Universal Time (UTC) value for a point in time input using a local
time zone value.
• If timezone is not provided, the current Windows time zone setting is used as the local
time zone target.
• If timezone is provided, the timezone string can either contain raw time zone informa-
tion in the format returned by @tzspec (p. 1156) or it can contain search text (such as
1174—Function Reference: U

a city name) found within one of the time zone descriptions returned by the function
@tzlist (p. 1155).

Examples
The commands
scalar dtime = @now
@utc(dtime, "-08:00")

convert local time at an 8 hour shift from UTC into UTC times.

If LOCALTIME is a series of local time values,


series utctime = @utc(localtime, "-05:00")

converts a series containing local time values at a 5 hour shift from UTC into a series con-
taining UTC times, for observations in the workfile sample.
series utctime = @utc(localtime, "Pacific")

converts a series containing local time values in U.S. Pacific Time Zone (including daylight
time adjustments) into a series containing UTC, for observations in the workfile sample.

if VLOCALTIME is a vector of time values,


vector vutctime = @utc(vlocaltime, "Stockholm")

converts the vector of local times in Stockholm, into UTC times.

Cross-references
See “Dates,” on page 104 and “Event Functions,” on page 311 for related discussion.

See also the related time zone functions @localt (p. 946), @tz (p. 1155), @tzlist
(p. 1155) and @tzspec (p. 1156).
@val—1175

Function Reference: V
@val.....................Number from a string (p. 1175).
@valcount ............Number of matching values (p. 1178).
@var ....................Population variance (no d.f. adjustment) (p. 1179).
@varp...................Population variance (no d.f. adjustment) (p. 1179).
@varpsby .............Population variances (non-d.f. corrected) of a series for each speci-
fied group (p. 1180).
@vars ...................Sample variance (d.f. adjusted) (p. 1181).
@varsby ...............Sample variances (d.f. corrected) of a series for each specified
group (p. 1181).
@varssby..............Sample variances (d.f. corrected) of a series for each specified
group (p. 1182).
@vcat ...................Vertically concatenate matrices (p. 1182).
@vec ....................Vectorize (stack columns of) matrix (p. 1183).
@vech ..................Vectorize (stack columns of) lower triangle of matrix (p. 1184).
@vernum..............EViews version number (p. 1184).
@verstr.................EViews product name string (p. 1184).

@val Element Functions

Number from a string.


Syntax: @val(arg[, fmt])
arg: string
fmt: (optional) numeric format string
Return: scalar

Returns the number that string arg represents. You may provide an optional numeric format
string fmt.

In most cases, EViews will be able to convert your string into the corresponding numeric
value without additional input. If EViews is unable to perform a conversion, it will return a
missing (NA) value.

There are a few important conventions used in the conversion process:


• A leading “$” in the string will be ignored.
• Strings enclosed in “( )” or with a leading “–” will be treated as negative numbers. All
other numeric strings, including those with a leading “+” will be treated as positive
numbers. You may not have a leading “+” or “–” inside of the parentheses.
1176—Function Reference: V

• A trailing “%” sign instructs EViews to treat the input string as a percentage—the
resulting value will be divided by 100.

There are some situations where you must provide a numeric format string so that EViews
can properly interpret your input. The syntax for the format string depends on the type of
number the string represents.
Real-Value Formats
EViews will properly interpret non-delimited decimal and scientific notation numeric input
strings as numbers.

If your string uses “,” to separate thousands, you should specify the “t” format string to
remove “,” delimiters prior to conversion. If the string uses “.” to separate thousands, you
should use “t..” to instruct EViews to remove “.” delimiters.

If your input string represents a number with suppressed decimal format, you should
include a format string beginning with the letter “s”:

s.precision suppressed decimal point format (precision determines


the number of digits to the right of the decimal)

EViews will divide the resulting number by 10 raised to the power of the specified precision.
The “s” format specification may be followed by a “t.” or a “t..” specification if necessary.
Integer Formats

r ratio (e.g., “30 1/5”).


i integer
h hexadecimal
o octal
b binary

You should use the “r”, “h”, “o”, or “b” formats to indicate that your input is in the speci-
fied format. The “i” format is generally not necessary unless you wish to produce a missing
value for a non-integer input string.

Examples
scalar num = @val("$1.23")

assigns the scalar NUM the numeric value 1.23.


series ser1 = @val("-$123.88")

returns the value -123.88.


scalar sperct = @val("478%")
@val—1177

divides the value by 100, setting the scalar SPERCT to 4.78.


scalar sratio = @val("(321 1/5)", "r")

sets the scalar SRATIO equal to -321.2


scalar shexa = @val("f01a", "h")

treats the string “f01a” as a hexadecimal number, converts it into the decimal equivalent,
61466, and assigns it to the scalar object SHEXA.
scalar sbin = @val("11110101", "b")

interprets the string “11110101” as a binary number, converts it into the decimal equivalent,
245, and assigns it to the scalar SBIN.

To ensure that a value is an integer, you may use the “i” option.
scalar sintna = @val("98.32", "i")
scalar sint = @val("96", "i")

SINTNA will contain a missing value NA since the input represents a non-integer value,
while SINT is set to 96.

You may use @val to convert values in an svector into a vector. The matrix command,
vector v = @val(sv1)

converts the string values of svector SV1 to numeric values and returns the values in the
svector V. If the vector V exists it will be sized to match the rows of SV1 and non-numeric
strings will be converted to NA.

The series command


series x = @val(alpha1)

converts the string values in the alpha series ALPHA1 to numeric values and returns the val-
ues in the series X. Non-numeric strings will be converted to NA.

Format strings may be used to govern the conversion,


vector vbin = @val(svbin, "b")

interprets the strings in the svector SVBIN as binary numbers, converts it into their decimal
equivalents and assigns it to the vector VBIN. If for example, SVBIN contained “110” “001”
and “010”, the resultant VBIN will contain 6, 1, and 2.

Cross-references
See @str (p. 1123) for tools for expressing numbers as strings.
1178—Function Reference: V

@valcount Basic Statistics

Count of matching values.


Syntax: @valcount(x, y)
x: data object
y: value or string
Return: number

The number of elements in x that match y. Note that numeric matches require an exact
match.

For series and alpha calculations, EViews will use the current or specified workfile sample.

Examples
Let X be a series of length 5 whose elements are 1, 2, 5, 4, 2. Then
= @valcount(x, 2)

returns 2, while
= @valcount(x, 2.000000000000000000001)

returns 0.

Consider the string vector A where


svector a = @sfill("pear", "bear", "ear")

Then the command


= @valcount(a, "ear")

returns the value 1, while


= @valcount(@right(a, 3), "ear")

returns 3.

Cross-references
See also @between (p. 725), @ebtw (p. 860).
@varp—1179

@var

Population Variance (no d.f. adjustment).

Population (non-d.f. adjusted) Pearson product moment variance.


Syntax: @var(x, [s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series
Return: number

The population variance is calculated as


T
1 2
VAR  ----
T   xt – x 
t1

where x is the mean of x .

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x = @rnd, then
= @var(x)

will return a value close to 1/12 in large samples.

Cross-references
See also @mean (p. 971), @skew (p. 1113), @kurt (p. 936), @varp (p. 1179), @vars (p. 1181),
and @stdev (p. 1117).

@varp

Population variance (no d.f. adjustment).

Population (non-d.f. adjusted) Pearson product moment variance.


Syntax: @varp(x, [s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigned to a
series
Return: number

The population variance is calculated as


1180—Function Reference: V

T
1 2
VAR  ----
T   xt – x 
t1

where x is the mean of x .

Equivalent to @var.

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x = @rnd, then
= @varp(x)

will return a value close to 1/12 in large samples.

Cross-references
See also @var (p. 1179), @vars (p. 1181), and @stdevp (p. 1118).

@varpsby

Population variances (non-d.f. corrected) of a series for each specified group.


Syntax: @varpsby(x, y[y1, y2, ... yn, s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Returns the Pearson product moment population (non-d.f. corrected) variance for x each
group defined by distinct values of y.

EViews will use the current or specified workfile sample.

Examples
show @varpsby(x, g1, g2)

produces a linked series of the by-group population variance of the series x, where members
of the same group have identical values for both g1 and g2.

Cross-references
See also @varsby (p. 1181) and @varssby (p. 1182).
@varsby—1181

@vars

Sample variance (d.f. adjusted).

Sample (d.f. adjusted) Pearson product moment variance.


Syntax: @vars(x, [s])
x: series, vector, matrix
s: (optional) sample string or object when x is a series and assigned to a
series
Return: number

The sample variance estimate is calculated as

1 T 2
VARS  -------------   x t – x 
T – 1t  1

where x is the mean of x .

For series calculations, EViews will use the current or specified workfile sample.

Examples
If x = @rnd, then
= @vars(x)

will return a value close to 1/12 in large samples.

Cross-references
See also @var (p. 1179), @varp (p. 1179), and @stdevs (p. 1119).

@varsby

Sample variances (d.f. corrected) of a series for each specified group.


Syntax: @varsby(x, y[y1, y2, ... yn, s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Returns the Pearson product moment population (d.f. corrected) variance for x each group
defined by distinct values of y.
1182—Function Reference: V

EViews will use the current or specified workfile sample.

Examples
show @varsby(x, g1, g2)

produces a linked series of the by-group population variance of the series x, where members
of the same group have identical values for both g1 and g2.

Cross-references
See also @varpsby (p. 1180) and @varssby (p. 1182).

@varssby

Sample variances (d.f. corrected) of a series for each specified group.


Syntax: @varssby(x, y[y1, y2, ... yn, s])
x: series
y series, alpha
s: (optional) sample string or object
Return: series

Returns the Pearson product moment population (d.f. corrected) variance for x each group
defined by distinct values of y.

EViews will use the current or specified workfile sample.

Examples
show @varssby(x, g1, g2)

produces a linked series of the by-group sample variance of the series x, where members of
the same group have identical values for both g1 and g2.

Cross-references
See also @varsby (p. 1181) and @varpsby (p. 1180).

@vcat

Vertically concatenate matrices.


Syntax: @vcat(m1, m2[, m3, ...])
m#: matrix, vector, svector or sym
Return: matrix
@vec—1183

Performs vertical concatenation of two matrix objects. Each of the m# must have the same
number of columns.

The result will have the sum of the number of rows and the same number of columns as the
m#.

For example, if m1 is a matrix with m rows and k columns, and m2 is a matrix with n rows
and k columns, then @vcat will return a matrix with (m+n) rows and k columns.

Examples
vector v1 = @fill(1, 2, 3)
matrix k1 = @vcat(v1, 2*v1, 3*v1)

produces the matrix K1 which vertically stack the vectors V1, 2*V1 and 3*V1.
matrix g1 = @mnrnd(3, 3)
sym s1 = @identity(3)
matrix m1 = @vcat(g1, s1, v1.@t)

stacks the random normal matrix G1 on top of the identity matrix, and the row vector con-
taining (1, 2, 3).

Cross-references
See also @hcat (p. 899).

@vec

Vectorize (stack columns of) matrix.


Syntax: @vec(m)
m: matrix, sym
Return: vector

Creates a vector from the columns of the given matrix stacked one on top of each other. The
vector will have the same number of elements as the source matrix.

Examples
matrix m1 = @mrnd(10, 3)
vector v1 = @vec(m1)

creates a 10  3 matrix of uniform random numbers M1 and stacks it into a 30 element vec-
tor V1.

Cross-references
See also @unvec (p. 1170), @unvech (p. 1171), and @vech (p. 1184).
1184—Function Reference: V

@vech

Vectorize (stack columns of) lower triangle of matrix.


Syntax: @vech(m)
m: matrix, sym
Return: vector

Creates a vector from the columns of the lower triangle of the source square matrix m
stacked on top of each another.

The vector has the same number of elements as the source matrix has in its lower triangle.

Examples
sym s1 = @mrnd(5, 5)
vector v1 = @vech(s1)

creates a 5  5 sym matrix S1 and stacks the elements in its lower triangle in a 15-element
vector V1.

If M is a matrix,
scalar is_symm = @vech(M)=@vech(M.@t)

tests for symmetry by seeing whether the lower and upper triangles of the matrix are equal.
If the upper and lower elements triangles are the same, then the equality test will return 1,
otherwise, it will return 0.

Cross-references
See also @unvec (p. 1170), @unvech (p. 1171), and @vec (p. 1183).

@vernum

Syntax: @vernum
Return: number

returns a number containing the EViews version number.

@verstr

Syntax: @verstr
Return: string
@verstr—1185

returns a string containing the EViews product name string (e.g. “EViews Enterprise Edi-
tion”).
1186—Function Reference: V
Function Reference: W—1187

Function Reference: W
@wcount ..............Number of words in the string list (p. 1188).
@wcross ...............String with words in first list crossed with second (p. 1188).
@wdelim ..............Replace delimiters in string (p. 1189).
@wdir ..................List of all files in a directory (p. 1190).
@wdrop................Drop words from string list (p. 1191).
@weekday ............Day of the week of the observation (p. 1192).
@wexpand............String representation of automatic dummy variables (p. 1192).
@wfattrnames.......String containing a list of attribute names in the workfile (p. 1194).
@wfattrvals ..........String containing a list of attribute values in the workfile (p. 1195).
@wfind.................Find location of word (case-sensitive) in string list (p. 1196).
@wfname .............String containing name of current workfile (p. 1198).
@wfindnc .............Find location of word (not case-sensitive) in string list (p. 1197).
@wfpath...............String containing path of current workfile (p. 1198).
@winsert ..............Insert string into string after word (p. 1199).
@winterleave........Interleave words of two string lists (p. 1200).
@wintersect..........Intersection of words in two string lists (p. 1201).
@wjoin.................Extract elements of an Svector to a string (p. 1202).
@wkeep ...............Keep subset of words in string list (p. 1202).
@wleft..................Left-most words of string list (p. 1203).
@wlookup ............String list formed from objects in a workfile or database matching a
pattern (p. 1204).
@wmid.................Middle or middle to end words of a string list (p. 1206).
@wnotin...............Words not in a string list (p. 1207).
@word .................Single word from a string list (p. 1208).
@wordq................Single word from a string list, preserving quotes (p. 1209).
@wquery..............String containing list of object attributes for objects matching a
database query (p. 1209).
@wread ................Read contents of text file into a string (p. 1210).
@wreplace............Replace characters in each word in a string list (p. 1211).
@wrfind ...............Find location of a word (case-sensitive) in a string list searching
from end (p. 1212).
@wrfindnc............Find location of a word (not case-sensitive) in a string list searching
from end (p. 1213).
@wright ...............Right-most words of a string list (p. 1214).
@wsort .................Sorted list of words in a string list (p. 1215).
@wsplit ................Create string vector from words in a string list (p. 1216).
@wunion..............Union of words in two string lists (p. 1216).
1188—Function Reference: W

@wunique ........... Remove duplicate words in string list (p. 1217).

@wcount Element Functions

Number of words in the string.


Syntax: @wcount(str_list)
str_list: string
Return: integer

Example
The commands
string s1 = "I did not do it"
@wcount("I did not do it")
@wcount(s1)

return the number 5.

If ALPHA1 is an alpha series,


scalar alphalwr = @wcount(alpha1)

returns the number of words in the strings in ALPHA1 for each observation in the workfile
sample.

If SVEC1 is an string vector,


vector sveclen = @wcount(svec1)

returns a the number of elements in each of the strings in SVEC1.

Cross-references
See also @len (p. 943) for the length of the strings.

@wcross Element Functions

String with words in first list crossed with second.


Syntax: @wcross(str_list1, str_list2[, pattern])
str_list1: string
str_list2: string
pattern: string
Return: string list
@wdelim—1189

Returns str_list1 crossed with str_list2, using the string pattern. The default pattern is “??”,
which indicates that each element of str_list1 should be crossed individually with each ele-
ment of str_list2.

Examples
@wcross("A B C", "1 2 3 4")

returns every combination of the elements “A B C” and “1 2 3 4”, using the default pattern
“??”. This produces the string list: “A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4”.
@wcross("ABC DEF", "1 2 3", "?-?")

returns the string list “ABC-1 ABC-2 ABC-3 DEF-1 DEF-2 DEF-3”, inserting a dash (“-”)
between each crossed element as the “?-?” pattern indicates.

If ALPHA1 is an alpha series,


alpha alphacx = @wcross(alpha1, "1 2 3 4")

crosses the string lists in ALPHA1 with “1 2 3 4” for each observation in the workfile sam-
ple.

If SVEC1 and SVEC2 are string vectors,


svector sveccx = @wcross(svec1, svec2)

crosses the string list in SVEC1 with the corresponding string list in SVEC2 for each element
of the two svectors.

Cross-references
See also @winterleave (p. 1200), @wintersect (p. 1201), and @wunion (p. 1216).

@wdelim Element Functions | String Functions

Replace delimiters in string.


Syntax: @wdelim(str_list, src_delim, dest_delim)
str_list: string
src_delim string delimiter
dest_delim string delimiter
Return: string

Returns a string list, replacing every appearance of the src_delim delimiter in str_list with a
dest_delim delimiter. Delimiters must be single characters.

Note that most other string list functions (those beginning with “@w”) require that the
delimiter be a space (“ ”). Use this function to convert strings with other delimiters into
those which can be used with the string list functions.
1190—Function Reference: W

Examples
@wdelim("Arizona, California, Washington", ",", "-")

identifies the comma as the source delimiter and replaces each comma with a dash, return-
ing the string “Arizona-California-Washington”.

If ALPHA1 is an alpha series,


alpha alphad = @wdelim(alpha1, ",", ":")

replaces each “,” with “:” in the string lists in ALPHA1, for each observation in the workfile
sample.

If SVEC1 is a vector,
svector svecd = @wdelim(svec1, ",", ";")

replaces each delimiter “,” with “;” in the string lists in SVEC1 for each element.

Cross-references
See also @wreplace (p. 1211) and @replace (p. 1070).

@wdir

Syntax: @wdir(d, t)
d: string
t: (optional) string
Return: string

The return_type may be one of the following:


“f” (default=”f”) Return the list of files in the directory_str directory.
“d” Return the list of directories in the directory_str directory.
“fd” Return the list of files and directories in the directory_str
directory. Note: directories will be denoted with a trailing \.

Returns a string list of all files/directories in the directory directory_str.

Examples
@wdir("C:\Documents and Settings")

returns a string list containing the names of all files in the “C:\Documents and Settings”
directory.
@wdir("C:\Documents and Settings", "fd")
@wdrop—1191

returns a string list containing the names of all files and directories in the “C:\Documents
and Settings” directory.

Cross-references
See also @fileexist (p. 883) and @folderexist (p. 888).

@wdrop Element Functions | String Functions

Drop words from string list.


Syntax: @wdrop(str_list, pat_list)
str_list: string
pat_list: string
Return: string

Returns a string list, dropping elements in str_list that match the string pattern pat_list. The
pat_list is space delimited and may be made up of any number of “?” (indicates any single
character) or “*” (indicates any number of characters).

The pattern is case-sensitive and must exactly match the str_list characters to be dropped.

Examples
@wdrop("D D A B C", "B D C")

removes each instant of the elements “B”, “D”, and “C”, returning the string “A”.
@wdrop("ABC DEF GHI JKL", "?B? D?? *I")

drops the first three elements of the string list, returning the string “JKL”. The string pattern
“?B?” drops “ABC”, the pattern “D??” drops “DEF”, and the pattern “*I” drops “GHI”.

If ALPHA1 is an alpha series,


alpha strdrop = @wdrop(alpha1, "B D C")

returns the string values of ALPHA1 after dropping “B D C” for each observation in the
workfile sample.

If SVEC1 is an string vector,


svector strdrop = @wdrop(svec1, "*I")

returns an svector after dropping all elements that end in “I” from each element of SVEC1.

Cross-references
See also @wkeep (p. 1202), @wnotin (p. 1207), @wunique (p. 1217).
1192—Function Reference: W

@weekday

Day of the week of the observation.


Syntax: @weekday
Return: series

Returns the day of the week (1–7) associated with each observation in the workfile (Mon-
day–Sunday).
• If the workfile is of lower than daily frequency, the day of the week will be first day of
the period.
• If the workfile is undated, observations will be set to -1.

Examples
series dt = @weekday
saves the day of the week into the series DT.
The command
workfile d7 2020 2022
smpl if @weekday < 7
creates a seven day workfile and sets the sample to exclude Sundays.

Cross-references
See also @day (p. 826), @hour (p. 910), @hourf (p. 910), @minute (p. 978), @month
(p. 983), @seas (p. 1109), @second (p. 1109), and @weekday (p. 1192).

@wexpand Special Expression

String representation of automatic dummy variables.

Return the string list associated with automatically created dummy variables from numeric
or alpha series.
Syntax: @wexpand(ser1[, ser2, ser3, ...][, s]))
ser1: series, alpha
ser2...: series, alpha
s: (optional) sample string or object
Return: string
@wexpand—1193

returns the string corresponding to the set of dummy variables that span the unique values
of the input series ser1, ser2, etc. These may be numerical series with integer only values,
alpha series or links.

By default, the definition of the categories will use the current workfile sample, but you may
specify an explicit sample s.

Example
For example, consider the following two variables:
• SEX is a numeric series which takes the values 1 and 0.
• REGION is an alpha series which takes the values “North”, “South”, “East”, and
“West”.

The command:
%str = @wexpand(sex)

yields the string SEXLIST containing “SEX=0 SEX=1”.

The @wexpand statement in,


%str = @wexpand(sex, region)

yields a space delimited string list SREGION with elements:


“SEX=0 AND REGION=""North""”
“SEX=0 AND REGION=""South""”
“SEX=0 AND REGION=""East""”
“SEX=0 AND REGION=""West""”
“SEX=1 AND REGION=""North""”
“SEX=1 AND REGION=""South""”
“SEX=1 AND REGION=""East""”
“SEX=1 AND REGION=""West""”

Cross-references
See “Automatic Categorical Dummy Variables” on page 1035 of User’s Guide II for further
discussion. See also @expand (p. 325).
1194—Function Reference: W

@wfattrnames

Syntax: @wfattrnames(attr[, obj, page, opt])


attr: string
obj: (optional) string
page: (optional) string
opt: (optional) integer
Return: string

Returns a string list of all attribute names that match the attr pattern in the specified page
list or active page and, optionally, whose object names also match the obj name pattern.
• The attr is a space delimited list of attribute name patterns. The list may be made up
of any number of names, or “?” (indicates any single character) or “*” (indicates any
number of characters) patterns.
• The obj list may be made up of any number of names, or “?” (indicates any single
character) or “*” (indicates any number of characters) patterns separated by spaces.
• The page list may be made up of any number of workfile page names, or “?” (indi-
cates any single character) or “*” (indicates any number of characters) patterns sepa-
rated by spaces. If a page list is not specified, only the active workfile page will be
used.
• The opt is an integer value indicating how a “*” or “?” in the attr should be treated
when matching. Use “0” to treat the characters as wildcards, and “1” to treat the char-
acters as literals.

Matches are not case-sensitive.

Examples
If a workfile contains three pages named “PAGE1”, “PAGE2”, and “PAGE3”,
@wfattrnames("M*")

returns the list of attributes for the objects in the active page that begin with “M”. Alterna-
tively,
@wfattrnames("M* S*", "*", "page1 page2")

returns the list of attributes for all the objects on PAGE1 and PAGE2 that begin with “M” and
“S”.

If an object on PAGE1 had an attribute named “*Note” and another object on the same page
had an attribute named “footnote” the command
@wfattrvals—1195

@wfattrnames("*NOTE", "*", "page1")

will return “*Note footnote” since the “*” in “*Note” is treated as a wildcard. However, the
command
@wfattrnames("*NOTE", "*", "page1", 1)

will return “*Note”, since the “*” in “*Note” is treated as a literal.

Cross-references
See also @attrnames (p. 718), @attrvals (p. 719), and @wfattrvals (p. 1195).

@wfattrvals

Syntax: @wfattrvals(attr[, obj, page, opt])


attr: string
obj: (optional) string
page: (optional) string
opt: (optional) integer
Return: string

Returns a string list of all attribute values that match the attr pattern in the specified page
list or active page and, optionally, whose object names also match the obj name pattern.
• The attr is a space delimited list of attribute value patterns. The list may be made up
of any number of names, or “?” (indicates any single character) or “*” (indicates any
number of characters) patterns.
• The obj list may be made up of any number of names, or “?” (indicates any single
character) or “*” (indicates any number of characters) patterns separated by spaces.
• The page list may be made up of any number of workfile page names, or “?” (indi-
cates any single character) or “*” (indicates any number of characters) patterns sepa-
rated by spaces. If a page list is not specified, only the active workfile page will be
used.
• The opt is an integer value indicating how a “*” or “?” in the attr should be treated
when matching. Use “0” to treat the characters as wildcards, and “1” to treat the char-
acters as literals.

Matches are not case-sensitive.

Examples
If a workfile contains three pages named “PAGE1”, “PAGE2”, and “PAGE3”, then
@wfattrvals("M*", "*", "PAGE1")
1196—Function Reference: W

return the string list of all attribute values that begin with “M” on PAGE1. Alternatively,
@wfattrvals("M* D*", "GDP", "PAGE1 PAGE2")

returns the list of attribute values for the objects PAGE1/GDP and PAGE2/GDP that begin
with “M” and “D”.

If on PAGE1 there was an object that had one attribute value of “*Mar” and second attribute
value of “Mar”, the command
@wfattrvals("*mar", "*", "PAGE1")

will return “*mar mar” since the “*” in “*mar” is treated as a wildcard and the values
“Mar” and “*Mar” both match the attribute list. However, the command
@wfattrvals("*mar", "*", "PAGE1", 1)

will only return “*mar”, since the “*” in “*Mar” is treated as a literal and only “*Mar”
matches the list.

Cross-references
See also @attrnames (p. 718), @attrvals (p. 719), and @wfattrnames (p. 1194).

@wfind Element Functions | String Functions

Find location of word (case-sensitive) in string list.


Syntax: @wfind(str_list, str_cmp)
str_list: string
str_cmp: string
Return: integer

Looks for the string str_cmp in the string list str_list, and returns the position in the list or 0
if the string is not in the list.
• This function is case-sensitive; use the @wfindnc (p. 1197) function to ignore case.
• Note that this function works only on single words; for multiple or parts of words, use
@instr (p. 924).

Examples
@wfind("I did it", "did")

returns the number 2, indicating the string “did” is second in the list.
@wfind("I did not do it", "i")

This function is case-sensitive and searches for the full string, so “i” will not be found and
the function will return the number 0.
@wfindnc—1197

If ALPHA1 is an alpha series,


series stfind = @wfind(alpha1, "did")

returns the position of the string word “did” in the string list values of ALPHA1 for each
observation in the workfile sample.

If SVEC1 is an string vector,


vector stfind = @wfind(svec1, "I")

returns the position of the string word “I” in the string lists in each element of SVEC1.

Cross-references
See also @instr (p. 924), @wfindnc (p. 1197), @wrfind (p. 1212), and @wrfindnc
(p. 1213).

@wfindnc Element Functions | String Functions

Find location of word (not case-insensitive) in string list.


Syntax: @wfindnc(str_list, str_cmp)
str_list: string
str_cmp: string
Return: integer

Looks for the string str_cmp in the string list str_list, and returns the position in the list or 0
if the string is not in the list.
• This function is similar to the @wfind (p. 1196) function, but is not case-sensitive
• Note that this function works only on single words; for multiple or parts of words, use
@instr (p. 924).

Examples
@wfindnc("I did it", "DID")

returns the number 2, indicating the caseless string “did” is second in the list.
@wfindnc("I did not do it", "i")

returns the number 1, since the first “i” or “I” encountered was in the first position.

If ALPHA1 is an alpha series,


series stfind = @wfindnc(alpha1, "did")

returns the position of the string word “did” caselessly matching the string list values of
ALPHA1 for each observation in the workfile sample.
1198—Function Reference: W

If SVEC1 is an string vector,


vector stfind = @wfindnc(svec1, "I")

returns the position of the string word “I” caselessly matching words in the string lists in
each element of SVEC1.

Cross-references
See also @instr (p. 924), @wfind (p. 1196), @wrfind (p. 1212), and @wrfindnc (p. 1213).

@wfname

Name of current default workfile.


Syntax: @wfname
Return: string

Returns a string containing the name of the current default workfile.

Examples
The command
string temp = @wfname

saves the current workfile name in the string variable TEMP, while
%tmp = @wfname + "bak"
wfsave %tmp

extracts the current workfile name, adds the text “bak” and then saves the current workfile
using the new name.

Cross-references
See also @pagename (p. 1029) and @wfpath (p. 1198).

@wfpath

Path of current default workfile.


Syntax: @wfpath
Return: string

Returns a string containing the path (location) of the current default workfile.

Examples
The command
@winsert—1199

string temp = @wfpath

saves the current workfile path in the string variable TEMP, while
%tmp = @wfpath + @wfname + "bak"
wfsave %tmp

extracts the current workfile path and name, adds the text “bak” and then saves the current
workfile using to the original path using the new name.

Cross-references
See also @wfname (p. 1198).

@winsert Element Functions | String Functions

Insert string into a string.


Syntax: @winsert(str1, str2, n)
str1: string
str2: string
n: integer
Return: string

Inserts the string str2 into the string str1 after the word position given by the integer n.

Examples
string sval1 = "I believe it can be done"
string sval2 = "not"
= @winsert("I believe it can be done", "not", 4)
= @insert(sval1, sval2, 4)
= @insert(sval1, "not”, 4)

all return the string “I believe it can not be done”.

If ALPHA1 is an alpha series,


alpha a1 = @winsert(sval2, "not", 4)

creates an alpha series with the contents of ALPHA1 with the string “not ” after word45, for
each observation in the workfile sample.
alpha a2 = @winsert(sval1, a1, ser1)

inserts SVAL1 into A1 after the integer word positions given in the series SER1.

If SVEC1 is an svector,
svector s1 = @winsert("(pretty please) ", svec1, 5)
1200—Function Reference: W

inserts “(pretty please) ” into SVEC at after word 4.

Cross-references
See also @wreplace (p. 1211), @insert (p. 923), @instr (p. 924), @rinstr (p. 1078), and
@mid (p. 974).

@winterleave Element Functions | String Functions

Interleave words of two string lists.


Syntax: @winterleave(str_list1, str_list2[, n1, n2])
str_list1: string
str_list2: string
n1: (optional) integer
n2: (optional) integer
Return: string

Interleaves str_list1 with str_list2, according to the pattern specified by n1 and n2. The
default uses counts of one.

Examples
@winterleave("A B C", "1 2 3")

interleaves “A B C” with “1 2 3” to produce the string list “A 1 B 2 C 3”.


@winterleave("A B C", "1 2 3 4 5 6")

interleaves “A B C” with “1 2 3 4 5 6”, returning the string list “A 1 B 2 C 3 “” 4”. Since there
are more elements in the second string, empty strings (“”) are inserted when the elements of
the first string run out.

Alternately, you may specify a count pattern to control the spacing of elements:
@winterleave("A B C", "1 2 3 4 5 6", 1, 2)

This command combines one element of the first string for every two elements of the second
string, returning “A 1 2 B 3 4 C 5 6”.

If ALPHA1 is an alpha series,


alpha alphacx = @winterleave(alpha1, "1 2 3 4")

interleaves the string lists in ALPHA1 with “1 2 3 4” for each observation in the workfile
sample.

If SVEC1 and SVEC2 are string vectors,


svector sveclen = @winterleave(svec1, svec2, 1, 2)
@wintersect—1201

interleaves the string list in SVEC1 with the corresponding string list in SVEC2 for each ele-
ment of the two svectors, using one element of the SVEC2 strings for every two elements of
the SVEC2 strings.

Cross-references
See also @wcross (p. 1188), @wintersect (p. 1201), and @wunion (p. 1216).

@wintersect Element Functions | String Functions

Intersection of words in two string lists.


Syntax: @wintersect(str_list1, str_list2)
str_list1: string
str_list:2 string
Return: string

Returns the elements that are in both str_list1 and str_list2. This function is case-sensitive.

Examples

@wintersect("John and Greg won", "Greg won with Mark's help")

returns the string “Greg won”.

Since this function is case-sensitive,


@wintersect("John and Greg won", "greg won with Mark's help")

just returns the string “won”.

If ALPHA1 and ALPHA2 are alpha series,


alpha stinter = @wintersect(alpha1, alpha2)

returns the intersection of values for elements of ALPHA1 and ALPHA2 for each observation
in the workfile sample.

If SVEC1 and SVEC2 are string vectors,


svector stinter = @wintersect(svec1, svec2)

returns an svector containing the intersection of the elements in SVEC1 and SVEC2 for each
element of the svectors.

Cross-Reference
See also @wcross (p. 1188), @winterleave (p. 1200), and @wunion (p. 1216).
1202—Function Reference: W

@wjoin

Extract elements of an Svector to a string.


Syntax: @wjoin(svec)
svec: svector
Return: string

Returns a space delimited list containing the elements of svec.

Examples
If svector SVEC has 7 rows with each row being the corresponding letter of the alphabet
(row 1 has “A”, row 2 has “B” and so on), then
@wjoin(svec)

returns a “A B C D E F G”.

Cross-Reference
See also @wsplit (p. 1216) for creating an svector from a string.

@wkeep Element Functions | String Functions

Keep subset of words in string list.


Syntax: @wkeep(str_list, pat_list)
str_list: string
pat_list: string
Return: string

Returns the list of elements in str_list that match the string pattern pat_list. The pat_list is
space delimited and may be made up of any number of “?” (indicates any single character)
or “*” (indicates any number of characters).

The pattern is case-sensitive and must exactly match the str_list characters to be kept.

Examples
@wkeep("D D A B C", "B D C")

returns all matching elements in pattern_list that are found in str_list: “D D B C”.
@wkeep("ABC DEF GHI JKL", "?B? D?? *I")
@wleft—1203

keeps the first three elements of the string list, returning the string “ABC DEF GHI”. The
string pattern “?B?” keeps “ABC”, the pattern “D??” keeps “DEF”, and the pattern “*I” keeps
“GHI”.

If ALPHA1 is an alpha series,


alpha strkeep = @wkeep(alpha1, "B* D* C*")

returns the string values of ALPHA1 keeping only word elements that begin with “B”, “D”,
or “C”, for each observation in the workfile sample.

If SVEC1 is an string vector,


svector strkeep = @wkeep(svec1, "*I")

returns an svector after keeping all elements that end in “I” from each element of SVEC1

Cross-references
See also @wdrop (p. 1191), @wnotin (p. 1207), @wunique (p. 1217).

@wleft Element Functions | String Functions

Left-most words of string list.


Syntax: @wleft(str_list, n)
str_list: string
n: integer
Return: string

Returns a string list containing the left n word elements of string list str_list. If the string list
str_list is shorter than n elements, this function returns all of the elements in the source
string.

Examples
The commands
string orig = "I did not do it"
string sc1 = @wleft("I did not do it", 2)
string sc2 = @left(orig, 2)

return the string objects SC1 and SC2 containing the string “I did”.

If ALPHA1 is an alpha series,


alpha strleft = @left(alpha1, 3)

returns the left-most 3 words from the string values of ALPHA1 for each observation in the
workfile sample.
1204—Function Reference: W

If SVEC1 is an string vector,


svector strleft = @left(svec1, 2)

returns an svector containing 2 words from the left end of each element of SVEC1.

Cross-references
See also @left (p. 942), @wright (p. 1214) and @wmid (p. 1206).

@wlookup

Lookup objects in workfile or database.


Syntax: @wlookup(obj[, type, [attr, [opt]]])
obj: string
type: (optional) string
attr: (optional) string
opt: (optional) integer
Return: string

Returns a string list of all objects in the workfile or database that match the name pattern
list and, optionally, the type object type list and the attr attribute pattern using the opt
search option.
• The obj list may be made up of any number of names, or “?” (indicates any single
character) or “*” (indicates any number of characters) patterns separated by spaces.
The pattern must exactly match the object name in the workfile or database.
• The type is a space delimited list containing one or more object types. The default is
“*”. Object types are "*", "sample", "svector", "equation", "graph", "table", "text",
"program", "model", "system", "var", "string", "pool", "sspace", "logl", "alpha",
"valmap", "factor", "spool", "graph", "userobj", "group+data", "group", "scalar",
"mat/vec/sym", "coeflist","group", "matveclist", "sym", "matrix", "vector", "coef",
"series", "link", "digraph", "geomap", "string", "formula", "database", and "work-
file".
• The attr is a space delimited list of attribute value patterns made up of any number of
names, or “?” (indicates any single character) or “*” (indicates any number of charac-
ters) patterns separated by spaces. The default is “”.
• The obj is an integer value indicating how a “*” in the attr should be treated when
matching. Use “0” to treat “*” as a wildcard and “1” to treat “*” as a literal. The
default is “0”.
@wlookup—1205

Examples
If a workfile contains three graph objects named “GRA1”, “GRA2”, and “GRA01”, one group
object named “GRO1”, and two series objects named “SR1” and “SER2”, then
@wlookup("GR*")

returns the string list “GRA01 GRA1 GRA2 GRO1”. All objects beginning with “GR” and fol-
lowed by any number of characters are included. Alternatively,
@wlookup("?R*")

returns the string list “GRA1 GRA2 GRA01 GRO1 SR1”. SER2 is not included because “?”
specifies a single character preceding an “R”.
@wlookup("?R?","series")

returns the string “SR1”. The object type “series” drops all graph objects from the list, and
“?R?” filters out SER2 because “?” specifies a single character.

Now let us assume for the same workfile:


• GRA1 had the attributes “Month” and “Author” with values equal to “September” and
“Sam”.
• GRA2 had the attribute “Author” with value equal to “Sam”.
• GRA01 had the attributes “Month” and “Author” with values equal to “January” and
“Mary”.
• GRO1 had the attribute “Month” with value equal to “September”.
• SRO1 had the attribute “Mon” with value equal to “January”.
• SER2 had the attributes “Month” and “Author” with values equal to “June” and
“Sam”.

We limit the results by adding attribute filters


@wlookup("GR*", "*”, "Month=J*")

returns the string list “GRA01”. “GRA01” was the only object that had the “Month” attribute
value beginning with “J”.
@wlookup("*", "*", "Month=September Month=J*")

returns the string “GRA01 GRA1 GRO1 SER2”. All objects either had a “Month” equal to
“September” or “Month” beginning with “J”.
@wlookup("*", "GRAPH", "Month=September Month=J*")

returns the string “GRA01 GRA1”. Only graph objects which either had a “Month” equal to
“September” or “Month” beginning with “J” are included.
@wlookup("*", "*", "Month=*")
1206—Function Reference: W

returns the string “GRA01 GRA1 GRO1 SER2”. All objects have a “Month” attribute whereby
the value is ignored.
@wlookup("*", "SERIES", "Month=*")

returns the string “SER2”. Only the series objects which have a “Month” attribute are
included.
@wlookup("*", "*", "M*th=September")

returns the objects which have attributes beginning with “M” and ending with “th”. This
returns the string “GRA1 GRO1”.

Cross-references
See also @wquery (p. 1209).

@wmid Element Functions | String Functions

Middle or middle to end words of a string list.


Syntax: @wmin(str_list, n1[, n2])
str_list: string
n1: integer
n2: (optional) integer
Return: string

Returns n2 elements from str_list, starting at element n1 and continuing to the right for n2
elements. If you omit n2, the function will return all of the remaining elements in the string.

Examples
The command
string s1 = @wmid("I really don’t doubt it", 4)

assigns “doubt it” to the string object S1, while


string s2 = @wmid("I really doubt it", 2, 2)

assigns “really doubt” to S2.

If ALPHA1 is an alpha series,


alpha strleft = @wmid(alpha1, 3)

returns the remaining words beginning with the 3rd from the string values of ALPHA1, for
each observation in the workfile sample.

If SVEC1 is an string vector,


svector strleft = @mid(svec1, 4, 2)
@wnotin—1207

returns an svector beginning at the 5th for 2 words for each element of SVEC1.

Cross-references
See also @mid (p. 974), @wleft (p. 1203) and @wright (p. 1214).

@wnotin Element Functions | String Functions

Words not in a string list.


Syntax: @wnotin(str_list1, str_list2)
str_list1: string
str_list2: string
Return: string

Returns elements of str_list1 that are not in str_list2. This function is case-sensitive.

Examples
string employee1 = @wnotin("Full Name: John Smith", "Full Name:")
string employee2 = @wnotin("Full Name: Mary Jones", "Full Name:")

assigns the string “John Smith” to the string object EMPLOYEE1, and the string “Mary
Jones” to the string object EMPLOYEE2.
@wnotin("John and Greg won", "and Greg")

returns the string “John won”.

If ALPHA1 is an alpha series,


alpha strnot = @wnotin(alpha1, "and or not")

returns the strings in ALPHA1 with the words “and”, “or”, and “not” removed, for each
observation in the workfile sample.

If SVEC1 is an string vector,


svector strnot = @wnotin(svec1, "and or not")

returns an svector with each string element of SVEC1 after removing “and”, “or”, and “not”.

Cross-references
See also @replace (p. 1070), @wdrop (p. 1191), @wkeep (p. 1202), @wreplace (p. 1211),
@wunique (p. 1217).
1208—Function Reference: W

@word Element Functions | String Functions

Single word from a string list.


Syntax: @word(str_list, n)
str_list: string
n: integer
Return: string

Returns the n-th element from the string list str_list, not including surrounding double-
quotes. This function is the same as the @wordq (p. 1209) function, but removes quotes.

Examples
@word("I don’t think so", 2)

returns the second element, “don’t”.


@wordq("""Chicken Marsala"" ""Beef Stew""", 2)

returns the second element, “Beef Stew”, without the surrounding double-quotes.

If ALPHA1 is an alpha series,


alpha str1 = @word(alpha1, 3)

returns the third word of the string lists in ALPHA1, while


alpha str2 = @word(alpha1, ser1)

returns the word in the string lists in ALPHA1 given by the integers in the series SER, for
each observation in the workfile sample.

If SVEC1 is an string vector,


svector str3 = @word(svec1, 5)

returns an svector with the fifth word in each element of SVEC1”.

Cross-references
See also @wordq (p. 1209).
@wquery—1209

@wordq Element Functions | String Functions

Single word from a string list, preserving quotes.


Syntax: @wordq(str_list, n)
str_list: string
n: integer
Return: string

Returns the n-th element from the string list str_list, retaining surrounding double-quotes.
This function is the same as the @word (p. 1208) function, but preserving quotes.

Examples
@wordq("""Chicken Marsala"" ""Beef Stew""", 2)

returns the second element, ‘“Beef Stew”’ including the surrounding double-quotes.

If ALPHA1 is an alpha series,


alpha str1 = @wordq(alpha1, 3)

returns the potentially quoted third word of the string lists in ALPHA1, while
alpha str2 = @wordq(alpha1, ser1)

returns the potentially quoted word in the string lists in ALPHA1 given by the integers in the
series SER, for each observation in the workfile sample.

If SVEC1 is an string vector,


svector str3 = @wordq(svec1, 5)

returns an svector with the potentially quoted fifth word in each element of SVEC1”.

Cross-references
See also @word (p. 1208).

@wquery

Object attributes from database query.


Syntax: @wquery(db[, str, attr])
db: string
str: (optional) string
attr: (optional) string
Return: string
1210—Function Reference: W

Returns a string list of object attributes for all objects in the database named db that satisfy
the query specified by str. The search expression str should be a standard database query.

By default @wquery will return the name of the objects in the database that match the
search criteria. However you may specify other object attributes to be returned, by listing
them (comma delimited) in attr.

Examples
If a database, MYDB, contains a series object named “GDP_1” and a series called “GDP_2”,
with the first being annual frequency and the second being quarterly frequency, then
@wquery("mydb", "name matches GDP* and freq=Q", "name")

returns the string “GDP_2”. Alternately,


@wquery("mydb", "name matches GDP* and freq=A", "name, freq")

returns the string list “GDP_1 A”.


@wquery("basics.edb", "freq = q and start>1970 and not
scale=millions")

returns a string list of the names of all objects in the database BASICS.EDB with quarterly
frequency and a start date after 1970 which do not have the custom attribute ‘scale’ set to
‘millions’.
@wunique(@wquery("mydb", "start>2000", "freq"))

returns a string list of all the frequencies of objects in the database whose start date is post
2000. Note that we use the @wunique function to remove duplicate frequencies from the list.

Cross-references
See also @wlookup (p. 1204).

@wread

Read contents of text file into a string.


Syntax: @wread(filespec[, mode])
filespec: file name of a text file on disk.
mode: string
Return: string

Returns a (potentially preprocessed) string containing the contents of the specified text file
on disk.
@wreplace—1211

The mode parameter specifies how the contents are parsed into individual fields and pro-
cessed before being concatenated and returned by the function. The mode parameter may be
used to specify a delimiter, or to instruct EViews to bypass preprocessing.

The following mode options specify the delimiter used to separate the input text into fields
prior to concatenation:
• “t” or “tabs” (tabs)
• “,” or “c”, or “comma” (commas)
• “cr” or “nl” (line breaks)

If no mode is specified, EViews will attempt to auto-detect the delimiter. If an individual


field contains double quotation marks, those marks will be escaped (replaced by "") and the
entire field will be surrounded by double quotation marks. Delimiters are removed from the
returned string, and all non-printing characters are replaced with spaces.

The following option for mode instructs EViews to return the contents of the file unmodified
with no field preprocessing:
• “raw”

Example
string s1 = @wread("c:\temp\myfile.txt")

returns a string containing the contents of “c:\temp\myfile.txt”. The contents of the file are
split into fields using autodetected delimiters, the delimiters are removed, and the fields are
concatenated using space delimiters with non-printing characters replaced with spaces.
string s2 = @wread("c:\temp\myfile.txt", "raw")

returns a string containing the raw contents of “c:\temp\myfile.txt”.

@wreplace Element Functions | String Functions

Replace characters in each word in a string list.


Syntax: @wreplace(str1, src_pat, rep_pat[, "all"])
str_list: string
src_pat: string
rep_pat: string
"all": (optional) string literal
Return: string

Replaces instances of str_list in str_list with rep_pat. The patterns may be made up of any
number of “?” (indicates any single character) or “*” (indicates any number of characters).
1212—Function Reference: W

The pattern is case-sensitive and must exactly match the src_pat characters to be replaced.

Only the first instance of src_pat within each word of str_list is replaced unless the optional
flag “all” is specified (enclosed in quotes), in which case all instances within each word are
replaced.

Examples
@wreplace("ABBC AB", "*B*", "*X*")

replaces the first instance of “B” with “X”, returning the string “AXBC AX”.
@wreplace("ABBC AB", "*B*", "*X*", "all")

replaces all instances of “B” with “X”, returning the string “AXXC AX”.
@wreplace("ABC DDBC", "??B?", "??X?")

replaces all instances of “B” which have two leading characters and one following character,
returning the string “ABC DDXC”.

If ALPHA1 is an alpha series,


alpha alphaltrim = @wreplace(alpha1, "*ABC*", "*X*", "all")

replaces all instances of “ABC” with “X” in each word of the entries of ALPHA1 for each
observation in the workfile sample.

If SVEC1 is an string vector,


svector sveclen = @wreplace(svec1, "In*", "")

returns a string vector containing elements of SVEC1 with the leading “In” in each word
removed.

Cross-references
See also @wdrop (p. 1191), @wkeep (p. 1202), @wnotin (p. 1207), and @replace (p. 1070).

@wrfind Element Functions | String Functions

Find location of a word (case-sensitive) in a string list searching from end.


Syntax: @wrfind(str_list, str_cmp)
str_list: string
str_cmp: string
Return: integer

Looks for the last occurrence of string str_cmp in the string list str_list, and returns the posi-
tion in the list or 0 if the string is not in the list.
• This function is case-sensitive; use the @wfindnc (p. 1197) function to ignore case.
@wrfindnc—1213

• Note that this function works only on single words; for multiple or partial words, use
@instr (p. 924).

Examples
= @wrfind("I did it. Did you?", "Did")

returns the number 4, indicating the string “Did” is 4th in the list.
= @wrfind("I did not do it", "i")

This function is case-sensitive and searches for the full word string, so “i” will not be found
and the function will return the number 0.

If ALPHA1 is an alpha series,


series stfind = @wrfind(alpha1, "did")

returns the last position of the string word “did” matching words in the string list values of
ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


vector stfind = @wrfind(svec1, "I")

returns the last position of the string word “I” matching words in the string lists in each ele-
ment of SVEC1.

Cross-references
See also @rinstr (p. 1078), @wrfindnc (p. 1213), @wfind (p. 1196), and @wfindnc
(p. 1197).

@wrfindnc Element Functions | String Functions

Find location of a word (not case-sensitive) in a string list searching from end.
Syntax: @wrfindnc(str_list, str_cmp)
str_list: string
str_cmp: string
Return: integer

Looks for last occurrence of the string str_cmp in the string list str_list, and returns the posi-
tion in the list or 0 if the string is not in the list.
• This function is the non-case-sensitive version of the @wrfind (p. 1212) function.
• Note that this function works only on single words; for multiple or partial words, use
@rinstr (p. 1078).
1214—Function Reference: W

Examples
= @wrfindnc("I did it. Did you?", "DID")

returns the number 4, indicating the last caseless string “did” is 4th in the list.
= @wrfindnc("I did not do it. I left early.", "i")

returns the number 6, since the last “i” or “I” word was in the 6th position.

If ALPHA1 is an alpha series,


series stfind = @wrfindnc(alpha1, "did")

returns the last position of the string word “did” caselessly matching the string list values of
ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


vector stfind = @wrfindnc(svec1, "I")

returns the last position of the string word “I” caselessly matching words in the string lists in
each element of SVEC1.

Cross-references
See also @rinstr (p. 1078), @wrfind (p. 1212), @wfind (p. 1196), and @wfindnc (p. 1197).

@wright Element Functions | String Functions

Right-most words of a string list.


Syntax: @wright(str_list, n)
str_list: string
n: integer
Return: string

Returns a string list containing the right n word elements of string list str_list. If the string
list str_list is shorter than n elements, this function returns all of the elements in the source
string.

Examples
The commands
string orig = "I did not do it"
string sc1 = @wright("I did not do it", 2)
string sc2 = @right(orig, 2)

return the string objects SC1 and SC2 containing the string “do it”.
@wsort—1215

If ALPHA1 is an alpha series,


alpha strrght = @right(alpha1, 3)

returns the right-most 3 words from the string values of ALPHA1 for each observation in the
workfile sample.

If SVEC1 is an string vector,


svector strrght = @right(svec1, 2)

returns an svector containing 2 words from the left end of each element of SVEC1.

Cross-references
See also @wright (p. 1214), @wleft (p. 1203) and @wmid (p. 1206).

@wsort Element Functions | String Functions

Sorted list of words in a string list.


Syntax: @wsort(str_list[, “d”])
str_list: string
“d”: (optional) string literal
Return: string

Returns sorted elements of str_list. Use the “d” flag to sort in descending order.

Examples
@wsort("expr1 aa1 fr3")

returns the sorted string “aa1 expr1 fr3”


@wsort("fq8 Fq8 xpr1", "d")

sorts the string in descending order: “xpr1 Fq8 fq8”.

If ALPHA1 is an alpha series,


alpha a1 = @right(alpha1, 3)

returns the sorted string list values of ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


svector s1 = @right(svec1, 2, "d")

returns an svector containing the descending order sorted string lists for each element of
SVEC1.
1216—Function Reference: W

@wsplit

Create string vector from words in a string list.


Syntax: @wsplit(str_list)
str_list: string
Return: svector

Returns an svector containing the elements of str_list.

Examples
If string list SS01 contains “A B C D E F”, then
svector s1 = @wsplit(ss01)

returns the svector S1, placing each word element of SS01 in a separate row, so that tow one
of S1 contains “A”, row two contains “B”, etc.

The command
svector s2 = @wsplit("apples oranges pears")

creates a 3 element svector S2, with the rows containing “apples”, “orange”, and “pears”.

Cross-references
See also @sfill (p. 1111). See @wjoin (p. 1202) for obtaining a string from an svector.

@wunion Element Functions | String Functions

Union of words in two string lists.


Syntax: @wunion(str_list1, str_list2)
str_list1: string
str_list2: string
Return: string

Returns the elements that are in either str_list1 and str_list2. This function is case-sensitive.

Examples

@wunion("ABC DEF", "ABC G H def")

returns the string “ABC DEF G H def”. Each new element is added to the string list, skipping
elements that have already been added to the list.

If ALPHA1 and ALPHA2 are alpha series,


@wunique—1217

alpha a1 = @wunion(alpha1, alpha2)

returns the union of values for elements of ALPHA1 and ALPHA2 for each observation in
the workfile sample.

If SVEC1 and SVEC2 are string vectors,


svector s1 = @wunion(svec1, svec2)

returns an svector containing the union of the elements in SVEC1 and SVEC2 for each ele-
ment of the svectors.

Cross-references
See also @wcross (p. 1188), @wintersect (p. 1201), and @winterleave (p. 1200).

@wunique Element Functions | String Functions

Remove duplicate words in a string list.


Syntax: @wunique(str_list)
str_list: string
Return: string

Returns str_list with duplicate elements removed from the list. This function is case-sensi-
tive.

Examples
@wunique("fr1 fr2 fr1")

returns the string “fr1 fr2”. Note that this function is case-sensitive, such that
@wunique("a A b B c c")

returns the string “a A b B c”.

If ALPHA1 is an alpha series,


alpha a1 = @wunique(alpha1)

returns the unique string list values of ALPHA1 for each observation in the workfile sample.

If SVEC1 is an string vector,


svector s1 = @wunique(svec1)

returns an svector containing the unique string lists for each element of SVEC1.

Cross-references
See also @wkeep (p. 1202), @wnotin (p. 1207), and @wunique (p. 1217).
1218—Function Reference: W
@xgetnum—1219

Function Reference: X
@xgetstr ...............String value from the external application.(p. 1219).
@xgetnum ............Scalar numeric value from the external application.(p. 1219).
@xputnames.........List of objects created in foreign application using XPUT (p. 1220).
@xtype .................Type of active external connection (p. 1220).
@xverstr ...............External application version number as a string (p. 1221).
@xvernum............External application version number as a number (p. 1221).

@xgetstr

Returns a string from the external application.


Syntax: @xgetstr(arg)
arg string
Return: string

returns the contents of arg in the external application. This function is similar to XGET but
does not require a workfile object to store the value.

Example
%y = @xgetstr("ss")

@xgetnum

Returns a scalar value from the external application.


Syntax: @xgetnum(arg)
arg string
Return: scalar

returns the contents of arg in the external application. This function is similar to XGET but
does not require a workfile object to store the value.

Example
!val = @xgetnum("ee")
1220—Function Reference: X

@xputnames

List of objects created in foreign application using XPUT.


Syntax: @xputnames
Return: string

returns a space delimited list containing the names of objects created in a foreign application
using the last xput (p. 675) command.

In most cases this list will contain EViews object names, but in cases where the object had a
name that was not valid in the foreign application, it will return the name that was created.

Examples
If you issue the commands:
xopen(r)
xput X Y LOG(Z)
string a = @xputnames

The string object A will contain "X Y LOG_Z".

Cross-references
See “EViews COM Automation Client Support (MATLAB, R, Python),” beginning on
page 195 for discussion. See also “External Program Interface” on page 2557 of User’s Guide
I for global options setting of the default case for names.

See also xput (p. 675).

@xtype

Type of external connection.


Syntax: @xtype
Return: string

Returns the string describing the type of the active external application:

• R connections return “rconn”.


• Matlab returns “m”.
• Python returns “pyconn”.

Returns an empty string if no external connection is active.


@xvernum—1221

Examples
string y = @xtype

returns “pyconn” if the external application type is Python.

@xverstr

Syntax: @xverstr
Return: string

Returns the external application version number as a string.

Example

%y = @xverstr

@xvernum

Syntax: @xgetstr(string)
Return: scalar

Returns the external application version number as a number.

Example
!i = @xvernum
1222—Function Reference: X
@ytd—1223

Function Reference: Y
@year...................Year of the observation (p. 1223).
@ytd ....................Within-year cumulative sum (year-to-date) (p. 1223).

@year

Year of observation.
Syntax: @year
Return: series

Returns the year associated with each observation in the workfile.


• If the workfile is undated, observations will be set to -1.

Examples
series dt = @year
saves the year into the series DT.
The command
workfile d7 2010 2022
smpl if @year < 2022
creates a seven day workfile and sets the sample include years prior to 2022.

Cross-references
See also @day (p. 826), @hour (p. 910), @hourf (p. 910), @minute (p. 978), @month
(p. 983), @seas (p. 1109), @second (p. 1109), and @weekday (p. 1192).

@ytd

Within-year cumulative sum (year-to-date).


Syntax: @ytd(x, y[, s])
x: series
y: series
s: (optional) sample string or object
Return: series

Cumulative sum of series x within each year, subject to limitations imposed by the workfile
or optional sample.

This function is panel aware.


1224—Function Reference: Y

Examples
If x is a series of monthly profits, then
show @ytd(x)

returns a linked series of year-to-date monthly profits.

Cross-references
See also @periodtodate (p. 1036).
@zeros—1225

Function Reference: Z
@zeros .................Matrix or vector of zeros (p. 1225).

@zeros

Matrix or vector of zeros.


Syntax: @zeros(n1, n2)
n1: integer
n2: integer
Return: matrix, vector

Creates a matrix or vector of the value 0. The size of the created matrix is given by the inte-
gers n1 (number of rows) and n2 (number of columns).

Examples
matrix m1 = @zeros(3,2)

creates M1, a 3  2 matrix of zeros.


sym s1 = @zeros(5, 5)
sym s2 = @unvech(@zeros(5*6/2))

create 5  5 symmetric matrices of zeros, while


vector v1 = @zero(18)
is an 18-element vector of zeros.

Cross-references
See also @identity (p. 913), @ones (p. 1018), and @unitvector (p. 1169).
1226—Function Reference: Z
Appendix A. Wildcards

EViews supports the use of wildcard characters in a variety of situations where you may
enter a list of objects or a list of series. For example, among other things, you can use wild-
cards to:
• fetch, store, copy, rename or delete a list of objects
• specify a group object
• query a database by name or filter the workfile display

The following discussion describes some of the issues involved in the use of wildcard char-
acters and expressions.

Wildcard Expressions
There are two wildcard characters: “*” and “?”. The wildcard character “*” matches zero or
more characters in a name, and the wildcard “?” matches any single character in a name.

For example, you can use the wildcard expression “GD*” to refer to all objects whose names
begin with the characters “GD”. The series GD, GDP, GD_F will be included in this list GGD,
GPD will not. If you use the expression GD?, EViews will interpret this as a list of all objects
with three character names beginning with the string “GD”: GDP and GD2 will be included,
but GD, GD_2 will not.

You can instruct EViews to match a fixed number of characters by using as many “?” wild-
card characters as necessary. For example, EViews will interpret “??GDP” as matching all
objects with names that begin with any two characters followed by the string “GDP”. USGDP
and F_GDP will be included but GDP, GGDP, GDPUS will not.

You can also mix the different wildcard characters in an expression. For example, you can
use the expression “*GDP?” to refer to any object that ends with the string “GDP” and an
arbitrary character. Both GDP_1, USGDP_F will be included.

Using Wildcard Expressions


Wildcard expressions may be used in filtering the workfile display (see “Filtering the Work-
file Display” on page 62 of the User’s Guide I), in selected EViews commands, and in creat-
ing a group object.

For example, the following commands support the use of wildcards: show (p. 589), store
(p. 600), fetch (p. 449), copy (p. 411), rename (p. 573) and delete (p. 432).
1228—Appendix A.Source and Destination Patterns

To create a group using wildcards, simply select Object/New Object.../Group, and enter the
expression, EViews will first expand the expression, and then attempt to create a group
using the corresponding list of series. For example, entering the list,
y x*

will create a group comprised of Y and all series beginning with the letter X. Alternatively,
you can enter the command:
group g1 x* y?? c

defines a group G1, consisting of all of the series matching “X*”, and all series beginning
with the letter “Y” followed by two arbitrary characters.

When making a group, EViews will only select series objects which match the given name
pattern and will place these objects in the group.

Once created, these groups may be used anywhere that EViews takes a group as input. For
example, if you have a series of dummy variables, DUM1, DUM2, DUM3, …, DUM9, that
you wish to enter in a regression, you can create a group containing the dummy variables,
and then enter the group in the regression:
group gdum dum?
equation eq1.ls y x z gdum

will run the appropriate regression. Note that we are assuming that the dummy variables are
the only series objects which match the wildcard expression DUM?.

Source and Destination Patterns


When wildcards are used during copy and rename operations, a pattern must be provided
for both the source and the destination. The destination pattern must always conform to the
source pattern in that the number and order of wildcard characters must be exactly the same
between the two. For example, the patterns,

Source Pattern Destination Pattern


x* y*
*c b*
x*12? yz*f?abc

which conform to each other, while these patterns do not:


Resolving Ambiguities—1229

Source Pattern Destination Pattern


a* b
*x ?y
x*y* *x*y*

When using wildcards, the new destination name is formed by replacing each wildcard in
the destination pattern by the characters from the source name that matched the corre-
sponding wildcard in the source pattern. This allows you to both add and remove characters
from the source name during the copy or rename process. Some examples should make this
clear:

Source Pattern Destination Pattern Source Name Destination Name


*_base *_jan x_base x_jan
us_* * us_gdp gdp
x? x?f x1 x1f
*_* **f us_gdp usgdpf
??*f ??_* usgdpf us_gdp

Note, as shown in the second example, that a simple asterisk for the destination pattern will
result in characters being removed from the source name when forming the destination
name. To copy objects between containers preserving the existing name, either repeat the
source pattern as the destination pattern,
copy x* db1::x*

or omit the destination pattern entirely,


copy x* db1::

Resolving Ambiguities
Note that an ambiguity can arise with wildcard characters since both “*” and “?” have mul-
tiple uses. The “*” character may be interpreted as either a multiplication operator or a wild-
card character. The “?” character serves as both the single character wildcard and the pool
cross section identifier.

Wildcard versus Multiplication


There is a potential for ambiguity in the use of the wildcard character “*”.

Suppose you have a workfile with the series X, X2, Y, XYA, XY2. There are then two interpre-
tations of the wildcard expression “X*2”. The expression may be interpreted as an auto-
1230—Appendix A.Wildcard versus Pool Identifier

series representing X multiplied by 2. Alternatively, the expression may be used as a wild-


card expression, referring to the series X2 and XY2.

Note that there is only an ambiguity when the character is used in the middle of an expres-
sion, not when the wildcard character “*” is used at the beginning or end of an expression.
EViews uses the following rules to determine the interpretation of ambiguous expressions:
• EViews first tests to see whether the expression represents a valid series expression. If
so, the expression is treated as an auto-series. If it is not a valid series expression,
then EViews will treat the “*” as a wildcard character. For example,
y*x
2*x
are interpreted as auto-series, while,
*x
x*a
are interpreted as wildcard expressions.
• You can force EViews to treat “*” as a wildcard by preceding the character with
another “*”. Thus, expressions containing “**” will always be treated as wildcard
expressions. For example, the expression:
x**2
unambiguously refers to all objects with names beginning with “X” and ending with
“2”. Note that the use of “**” does not conflict with the EViews exponentiation opera-
tor “^”.
• You can instruct EViews to treat “*” as a series expression operator by enclosing the
expression (or any subexpression) in parentheses. For example:
(y*x)
always refers to X times Y.

We strongly encourage you to resolve the ambiguity by using parentheses to denote series
expressions, and double asterisks to denote wildcards (in the middle of expressions), when-
ever you create a group. This is especially true when group creation occurs in a program;
otherwise the behavior of the program will be difficult to predict since it will change as the
names of other objects in the workfile change.

Wildcard versus Pool Identifier


The “?” wildcard character is used both to match any single character in a pattern and as a
place-holder for the cross-section identifier in pool objects.
Wildcard versus Pool Identifier—1231

EViews resolves this ambiguity by not allowing the wildcard interpretation of “?” in any
expression involving a pool object or entered into a pool dialog. “?” is used exclusively as a
cross-section identifier. For example, suppose that you have the pool object POOL1. Then,
the expression,
pool1.est y? x? c

is a regression of the pool variable Y? on the pool variable X?, and,


pool1.delete x?

deletes all of the series in the pool series X?. There is no ambiguity in the interpretation of
these expressions since they both involve POOL1.

Similarly, when used apart from a pool object, the “?” is interpreted as a wildcard character.
Thus,
delete x?

unambiguously deletes all of the series matching “X?”.


1232—Appendix A.Wildcard versus Pool Identifier
Index

Symbols downloading 207


examples 215
716, 721, 725, 737, 772, 814, 826, 827, 829,
installation 207
854, 860, 870, 878, 901, 905, 910, 921, 930,
installer file 228
978, 983, 1016, 1017, 1024, 1025, 1026, 1027,
management 220
1028, 1029, 1030, 1109, 1128, 1192, 1198
naming 225
– (dash)
register 365
negation 294
registration 223
subtraction 295
removing 221
_ (continuation character) 130
table of contents file 227
_this 230
TOC ini 227
! (exclamation) control variable 143
using 207, 211
?
@addinspath 714
wildcard versus pool identifier 1230
Addition operator (+) 294
’ (comment character) 130, 142
@addquotes 96, 715
{ 147
addtext 50
* (asterisk) multiplication 295
adduo 367
/ (slash) division 296
@after 312, 716
% (percent sign)
AIPZ file 226
program arguments 151, 155, 156
@all 593
string variable 101, 145, 146
Alpha series
+ (plus)
unique values 1169
addition 294
Alphabetizing 87
~, in backup file name 131
Analytical derivatives
user defined optimization 264, 527
Numerics and 681
1-step GMM Andrew’s automatic bandwidth
single equation 468 cointegrating regression 404, 407
2sls (Two-Stage Least Squares) 607, 612 robust standard errors 386, 610
Andrews automatic bandwidth
A robust standard errors 377, 512
@abs 713 ar 323
abs 713 AR specification
autoregressive error 323
Absolute value 713
seasonal 329
@acos 714
Arc cosine 714
Activate
Arc sine 717
workfile 665
Arc tangent 714, 718
addin 365
ARCH
Add-ins 207
See also GARCH.
adding 223
creating 222, 226 ARCH-M 370
definition 207 archtest 374
delete 433, 443 ARDL 375
directory 222, 714 ardl 375
1234—Index

ARFIMA specification 324 B


Arguments
Backcast
in programs 155
in GARCH models 370
in subroutines 169
MA terms 511
@asc 717
Backup files 131
ASCII code 717, 744
Backwards cumulative statistics
ASCII file
maximum 777
open file as workfile 640
mean 777
@asin 717
median 778
Assign values to matrix objects 280
minimum 779
by element 280
NAs, number of 780
converting series or group 290
observations, number of 780
copy 285
product 781
copy submatrix 287, 290
quantiles 782
fill procedure 281
standard deviation 783, 784, 785
@atan 714, 718
sum 786
Attributes 638 sum of squared values 786
importing 487 variance 787, 788, 789
list of 718, 1194
Bandwidth
list of values 719, 1195
cointegrating regression 404, 407
viewing 638
GMM estimation 377, 386, 512, 610
@attrnames 718
Bartlett kernel
@attrvals 719 cointegrating regression 404, 406, 407
Augmented Dickey-Fuller test 619 GMM estimation 470
Australian Bureau of Statistics robust standard errors 377, 385, 512, 610
ABS 429 Batch mode 136
auto 381 See also Program.
Auto-complete BEA 429
command 9 @before 312, 721
object name 8 Beta
Automatic bandwidth selection integral 722
cointegrating regression 404, 407 integral, logarithm of 725
robust standard errors 377, 386, 512, 610 @beta 722
Automation 195 @betainc 723
See Programs.
@betaincder 723
Autoregressive conditional heteroskedasticity
@betaincinv 724
See ARCH and GARCH.
@betalog 725
Autoregressive distributed lag 375
@between 320, 725, 860
Autoregressive error. See AR.
binary 382
Auto-search/GETS 625
Binary dependent variable 382
Auto-updating series
Binary file 640
convert to ordinary series 561, 618, 664
@binom 726
Autowrap 129
Binomial
Auxiliary commands 27
coefficient function 726
summary 357
coefficients, logarithm of 726
Axis
@binomlog 726
customization by command 42
Black and white 40
location by command 45
Blom 1057
C—1235

Bloomberg data 429 CEIC 429


BLS 429 @ceil 737
Bohman kernel Cell
cointegrating regression 404, 406, 407 display format 62
GMM estimation 470 formatting 62
robust standard errors 377, 385, 512, 610 @cellid 320, 737
Bollerslev-Wooldridge censored 389
See ARCH. Censored dependent variable 389
Boolean cfetch 391
and 681 @cfirst 740
or 682 Change default directory 388
Bootstrap Cholesky 743
rows of matrix 1071 @cholesky 743
Bounded values 727 chow 392
@bounds 727 Chow test 392
Break 136 Chow-Lin
breakls 384 frequency conversion method 414
Breakpoint estimation 384 @chr 744
Breakpoint test 392, 446 @cifirst 744
See also Breakpoint estimation @cilast 745
estimation after 384 @cimax 746
Breakpoints 137 @cimin 746
Breitung 619 @cintercept 747
Breusch-Godfrey test clabel 393
See Serial correlation. @clast 748
@bridge 727 clearerrs 393
Bridge missing values 727 @cloglog 749
Bureau of Economic Analysis 429 Close
Bureau of Labor Statistics 429 EViews 446
window 393
C workfile 631
@cagr 732 close 393
call 347 Cloud drive 389, 644, 662
Call stack 137 @cmax 750
Call subroutine 171 @cmean 751
Canonical cointegrating regression 402 @cmedian 751
@capplyranks 733, 758, 1065 @cmin 752
Case-sensitivity 190 @cnas 752
Categorize 702 @cobs 754
Category identifier coint 395
index 702 Cointegrating regression 402
number of 702 Cointegration
Causality Engle-Granger test 395
Granger’s test 387 Phillips-Ouliaris test 395
cause 387 test 395
ccopy 388 cointreg 402
cd 388 @colcumprod 754
@cdetrend 757 @colcumsum 755
1236—Index

@coldemean 756 Command explorer 6


colplace 410 Command window 5
@colstdize 760 docking and moving 10
@colstdizep 761 commandcap 410
Column Commands
extract from matrix 762 auxiliary 27, 357
number of columns in matrix 759, 762 basic command summary 357
number of matching values 806 batch mode 17
place in matrix 410 capture from user-interface 3
stack matrix 1183 documentation 476
stack matrix (lower triangle) 1184 execute without opening window 435
unstack into matrix 1170 interactive mode 5
unstack into sym (lower triangle) 1171 object assignment 19
Column statistics object command 21
First non-missing 740 object declaration 21
First non-missing index 744 save record of 3, 5
intercept from trend regression 747 Comments 81
last non-missing 748 program 130, 142
last non-missing index 745 Commutation matrix 763
maximum 750 @commute 763
maximum index 746 Comparing workfiles and pages 632
means 751 Comparison operators 296
median 751 Compatibility 188
minimum 752 Complementary log-log function 749
minimum index 746 Component GARCH 369
NAs, number of 752 Compound annual growth rate 732
observations, number of 754 Compound growth rate 1032
sum of squares 774 Concatenation 86
sums 774 @cond 763
Column width 60, 586 Condition number of matrix 763
@columnextract 762 Container 27
@columns 759, 762 database 28
COM session workfile 27
close 668 Continuation character in programs 130
command line 671, 672 Continuously updating GMM
EViews as client 195 single equation 468
EViews as server 195 Control variable 143
EViews log 671 as replacement variable 149
get object 668 in while statement 164
open 672 save value to scalar 144
put names 1220 Convergence criterion 511, 513, 520
R packages 674 Convert
run command 677 alpha to svector 598
send object 675 date to observation number 847
Command matrix object to series or group 522
object command auto-complete 9 matrix objects 290
object name auto-complete 8 matrix to sym 919, 920
Command capture 3 observation number to date 99, 100, 1019, 1020
add comment 410
C—1237

pool to panel 555 @cstdevs 773


scalar to string 1123 @csum 774
series or group to matrix (drop NAs) 598, 764 @csumsq 774
series or group to matrix (keep NAs) 599 @ctrendcoef 775
series to matrix/vector 292 @ctrmean 776
string to scalar 99, 146, 1175 @cumbmax 777
sym to matrix 880 @cumbmean 777
table to matrix 617 @cumbmedian 778
@convert 292, 764 @cumbmin 779
Copy @cumbnas 780
database 424 @cumbobs 780
matrix 285 @cumbprod 781
objects 30, 411 @cumbquantile 782
workfile page 538 @cumbstdev 783
copy 411 @cumbstdevp 784
@cor 766 @cumbstdevs 785
cor 418 @cumbsum 786
Correlation 766 @cumbsumsq 786
cross 422 @cumbvar 787
matrix 418 @cumbvarp 788
Correlogram 422 @cumbvars 789
@cos 766 @cumdn 790
Cosine 766 @cumdp 791
count 419 @cumdz 792
Count models 419 @cummax 793
@cov 767 @cummean 794
cov 421 @cummedian 794
Covariance 767, 768, 769 @cummin 795
matrix 421 @cumnas 796
@covp 768 @cumobs 797
@covs 769 @cumprod 797
@cprod 771 @cumquantile 798
Create @cumstdev 799
database 424, 426 @cumstdevp 800
graph by command 33 @cumstdevs 801
program 129
@cumsum 802
spool by command 77
@cumsumsq 803
table 57
Cumulative distribution
workfile 634
computation 1057
workfile page 540
Cumulative product
cross 422
matrix column 754
Cross correlation 422
Cumulative statistics
Cross product 1021
difference of the sum of negative (below thresh-
@crossid 320, 772
old) differences 831
Cross-section difference of the sum of positive (above thresh-
identifier 737 old) differences 832
@cstdev 772 difference of the sum of zero (at threshold) differ-
@cstdevp 773 ences 833
1238—Index

maximum 793 EIA 429


mean 794 fetch objects 449
Median 794 find objects 1204
minimum 795 Haver Analytics 476, 477, 478
NAs, number of 796 open 29
observations, number of 797 open existing 428
product 797 open or create 424
Quantiles 798 pack 431
standard deviation 799, 800, 801 query 1209
sum 802 rebuild 431
sum of negative (below threshold) differences rename 29, 432
790 Statistics Canada SDMX 430
sum of positive (above threshold) differences 791 store object in 600
sum of squared values 803 support for custom 203
sum of zero (at threshold) differences 792 @datapath 813
variance 803, 804, 805 Datastream 429
Cumulative sum Date
matrix column 755 first matching 930
@cumvar 803 @date 122, 308, 814
@cumvarp 804 Date functions 308
@cumvars 805 @dateadd 120, 815
Current @dateceil 819
time function 1146 @datediff 120, 817
Custom database 203 @datefloor 121, 820
@cvar 807 @datenext 821
@cvarp 807 @datepart 121, 823
@cvars 808 Dates
arithmetic 120, 815, 817, 819, 820, 821, 960
D convert from observation number 100, 1019,
d 324, 812 1020
convert string to date 825
Daniell kernel
convert to observation number 847
cointegrating regression 404, 406, 407
converting from numbers 116
GMM estimation 470
current as string 1132
robust standard errors 377, 385, 512, 610
current date and time 122, 1013
Data
current date as a string 100
access EViews data 194
date arithmetic 120, 121
custom database support 203
date associated with observation 122
enter from keyboard 423
date numbers 106
EViews Database Objects (EDO) 194
date operators 119
import 480, 640
date strings 105
import as matrix 489
extract portion of 121, 823
import as table 496
format strings 106
data 423
formatting 106
Data members 25
@-functions 122
Database
functions 122
copy 29, 424
make from formatted number 960
create 28, 426
rounding 121
delete 29, 428
string representations 98, 105, 115, 824, 825
D—1239

two-digit years 112, 125 Detrend data 836


workfile dates as strings 99, 123, 310 Deutsche Bundesbank 429
@datestr 115, 824 Diagonal
@dateval 98, 115, 825 get main diagonal from a matrix 895
@day 122, 309, 593, 826 Diagonal matrix 961
Day of month 826 Dialogs
Day of week 1192 user-defined 178
@daycount 312, 827 Dickey-Fuller test 619
Days did 434
count of 312 Difference
db 424 fractional 889
dbcopy 424 Difference operator 812
dbcreate 426 DIfference-in-difference 434
dbdelete 428 Digamma function 839, 1043
@dbname 829 Directory
DBnomics 429 change working 388
dbopen 428 data 813
dbpack 431 EViews add-ins 714
dbrebuild 431 EViews executable 878
dbrename 432 temporary files 1145
@dcumdn 831 Display
@dcumdp 832 action 21
@dcumdz 833 and print 23
Debugging objects 589
program dependencies 139 Display format 62
programs 137 Divide
Declaring objects 21 Division operator (/) 296
Default matrix element by element 861, 869
name of workfile 1198 dlog 842
Delete do 435
database 428 Double exponential smoothing 590
objects 31, 432 DRI database
workfile page 546, 547, 656 convert to EViews database 436
delete 432 copy from 388
deleteaddin 433, 443 fetch series 391
@demean 834 read series description 393
Demean by group data 835 driconvert 436
Demean data 756, 834 Dropbox 389, 644, 662
@demeanby 835 @dtoc 847
Denton Dummy variables
frequency conversion method 414 automatic creation 325, 1192
Dependencies 139 functions 311, 320
Descriptive statistics 477 @dupids 852
@det 835 @duplic 849, 850
Determinant 835 Duplicates
Detrend enumerating observations 851
columns of matrix 757 group identifier 852
@detrend 836 number of observations 853
1240—Index

Duplication matrix 849, 850 See also Unit root tests.


@dupselem 851 else 347
@dupsobs 853 Else clause in if statement 158, 159, 347
Durbin's h 169 @elt 867
@during 312, 854 @emax 868
Dynamic forecasting 455 @emin 868
Dynamic OLS (DOLS) 402 Empty string 926
Encrypted program file 133
E End date 870
ECB 429 @enddate 308, 870
@ediv 861, 869 endif 348
EDO (EViews Database Objects) 194 endsub 348
EDX interface 203 @eneq 870
@eeq 861 @eneqna 871
@eeqna 862 enet (Elastic Net) 436
EGARCH 368 @enisna 872
See also GARCH Enter data from keyboard 423
@ege 863 @env 872
@egt 863 Enviroment variables
EIA 429 Windows 872
Eigenvalues 864 @epow 873
@eigenvalues 864 @eqna 91, 873, 927
Eigenvectors 864 @equaloption 157, 875
@eigenvectors 864 Equals comparison 296
matrix element by element 861, 862
@eisna 865
Equation
Elapsed time 611, 1146
variable selection 625
@ele 866
@erecode 876
@elem 305
@erf 876
Element
@erfc 877
assign in matrix 280
Error function 876
Element by element
complementary 877
division 861, 869
equality 861, 862 @errorcount 877
greater than 863 Errors
greater than or equal to 863 codes in programs 941
inequality 870, 871 control 165
inverse 865 count in programs 393, 877
is missing value 865 handling in programs 165
is not missing value 872 maximum number in programs 588, 966
Less than 867 message in programs 942
less than or equal to 866 number in programs 587
maximum 868 Estimation
minimum 868 cointegrating regression 402
raise to power 873 user-defined 261, 525
recode 876 Estimation methods
@elim 867 2sls 607, 612
Elimination matrix 867 ARMA 510
Elliot, Rothenberg, and Stock point optimal test 620 cointegrating regression 402
F—1241

generalized least squares 510, 519 function 879


GMM 467 function minus 1 880
least squares 474, 510, 519 Exponential GARCH (EGARCH) 368
nonlinear least squares 474, 510, 519 See also GARCH
varsel 625 Exponential smoothing 590
Estimation methods Holt-Winters additive 591
enet 436 Holt-Winters multiplicative 591
Euler’s constant 892 Holt-Winters no seasonal 591
Eurostat database 429 Export 548
@event 312, 878 matrix 303
Event functions 311 tables 73
Event indicator 878 workfile data 548, 656, 666
EViews Extending EViews
add-ins directory 714 See Add-ins.
data directory 813 External application
installation directory 878 string 1220
spawn process 596 External program 195, 596
version number 1184 Extract
EViews database 429 row vector 1089, 1090
EViews Database Extension (EDX) interface 203 submatrix from matrix 1133
@evpath 878
Excel F
Add-in 194 facbreak 446
Excel file 640, 666 @fact 881
export data to file 656, 659, 666 factest 447
importing data into matrix 489
@factlog 882
importing data into table 496
Factor breakpoint test 446
importing data into workfile 480, 570
Factor object
retrieve sheet names 1143
command for estimation 447
exec 167
Factorial 881
Execute program 133, 444, 581
log of 882
abort 136
FAME database 429
with arguments 151, 155, 156
Federal Reserve Economic Data 429
Exit
Fetch
from EViews 446
object 32, 449
loop 166, 348
fetch 449
subroutine 351
Ffunctional coefficients estimation 460
exit 446
FIEGARCH 369
exitloop 348
FIGARCH 369
@exp 879
@fileexist 883
exp 879
Files
@expand 325
check for existence of 883
@explode 880
directory list 100, 1190
@expm1 880
open program or text file 524
Exponent 1041
opening/saving on a cloud location 389, 644,
Exponent minus 1 1042
662
Exponent of 1 plus, minus 1 1041 temporary location 1145
Exponential Fill
1242—Index

matrix 281, 884 mark end 350


row vector 885 nesting 161
symmetric matrix 885 roundoff error in 352
vector 281, 884, 886 start loop 349
@fill 884 step size 352
@filledmatrix 884 upper limit 354
@filledrowvector 885 Forecast
@filledsym 885 dynamic (multi-period) 455
@filledvector 886 static (one-period ahead) 452
Filter forecast 455
Hodrick-Prescott 479 Foreign data
Filter workfile display 639 open as workfile 640
Financial function save workfile data as 656
future value 889 Foreign file
number of periods 1013 retrieve table/sheet names 1143
payment amount 1040 Format
present value 1044 number 59
rate for annuity 1066 Formula series 458
Find @fracdiff 889
workfile and database objects 1204 Fractional difference 889
workfile objects 100 Fractional differencing parameter 324
@first 593, 886, 914 Fractional EGARCH 369
First non-missing Fractional GARCH 369
matrix columns 740 FRED 429
matrix columns index 744 Freeze 457
vector or series 886 table 57
vector or series index 914 freeze 457
@firstmax 593 Frequency
@firstmin 593 number of matching values 806, 1178
Fisher-ADF 619 page 1025
Fisher-Johansen 400 retrieving from a workfile or page 306
Fisher-PP 619 Frequency conversion 411
fit 452 Chow-Lin 414
Fitted index 453 data bases 449
Fitted values 452 Denton 414
@floor 887 linear 414
@folderexist 888 Litterman 414
Folders panel data 415
check for existence of 888 point 414
for 349 quadratic 414
For loop 160 frml 458
accessing elements of a series 161 Fully modified OLS (FMOLS) 402
accessing elements of a vector 161 funcoef 460
changing samples within 161 Functional coefficients
define using control variables 160 estimate 460
define using scalars 162 Functions
define using string variables 162 holidays 313
exit loop 166 @-functions
H—1243

workfile 305 continuously updating (single equation) 468


Future value 889 estimate single equation by 467
@fv 889 iterate to convergence (single equation) 468
one-step (single equation) 468
G gmm 467
Gompit models 382
@gamma 891
Google Drive 389, 644, 662
Gamma function 891
Gradients
derivative 839, 892, 1043
in user defined optimization 264, 527
incomplete 892
Granger causality test 387
incomplete derivative 893
incomplete inverse 894 Graph
logarithm 894 add text 50
second derivative 1152 axis by command 42
axis location by command 45
@gammader 892
change types 37
@gammainc 892
color by command 39
@gammaincder 893
create by command 33
@gammaincinv 894
create using freeze 457
@gammalog 894
customization by command 38
GARCH
frame customization by command 47
estimate equation 368
label by command 54
exponential GARCH (EGARCH) 369
legend by command 49
Fractional Exponential GARCH (FIEGARCH) 369
line characteristics 39
Fractional GARCH (FIGARCH) 369
merge 37
Integrated GARCH (IGARCH) 370
patterns by command 40
Power ARCH (PARCH) 369
save to disk 583
test for 374
shading by command 51
Gauss file 640, 656
size by command 47
Gauss-Newton 511
template by command 51
Generalized autoregressive conditional heteroske-
Greater than comparison 296
dasticity
matrix element by element 863
See ARCH and GARCH.
Greater than or equal to comparison 296
Generalized inverse 1038
matrix element by element 863
Generalized linear models
Grid 897
Generate series 462
@grid 897
genr 462
Group
See also alpha.
convert to matrix 292, 522
Geometric mean 896
convert to matrix (keep NAs) 599
@getmaindiagonal 895 creating using wildcards 1228
@getnextname 895 test for valid group specification 931
getthistype 896 @groupid 702
GLM Growth rate
See Generalized linear models. compound 1032
GLM standard errors 382, 420, 465, 532 compound annual 732
Global subroutine 173 Gumbel 1057
Global variable 173
GLS 510 H
@gmean 896
GMM HAC
1244—Index

GMM estimation 469 matrix comparisons 159


robust standard errors 376, 385, 512, 513, 609 start of condition 349
Hadri 619 then 353
Harmonic mean 900 @iff 915
@hasoption 156, 899 IGARCH 370
Haver Analytics Database 429 IHS 429
convert to EViews database 476 IHS Global Insight data 429
display series description 478 IHSMarkit 429
fetch series from 477 Im, Pesaran and Shin 619
@hcat 899 @imax 916
hconvert 476 @imaxes 917
heckit 474 IMF 429
help 476 @imin 918
Hessian matrix @imins 918
user defined optimization 265, 273, 527, 528 @implode 919
hfetch 477 @implodeu 920
hist 477 import 480
Histogram 477 Import data 480, 640
hlabel 478 as matrix 489
@hmean 900 as table 496
Hodrick-Prescott filter 479 matrix 302
@holiday 313, 901 importattr 487
Holiday (multiple) event indicator 905 importmat 489
Holiday event indicator 901 importtbl 496
Holiday variables 313 Impute NAs 727
Holidays 313 Include
@holidayset 313, 905 file in a program file 349
Holt-Winters 590 program file 168
Horizontal matrix concatenation 899 include 349
@hour 122, 309, 593, 910 Incomplete beta 723
Hour of day 910 derivative 723
@hourf 123, 310, 593, 910 inverse 724
hpf 479 Incomplete gamma 892
HTML derivative 893
open page as workfile 640 inverse 894
save table as 73 @incr 920
Huber/White standard errors 371, 376, 382, 390, Increment rows or columns of matrix 920
420, 465, 475, 512, 513, 520, 532, 604 Indentation 63
Index
I fitted from binary models 453
fitted from censored models 453
Identifier series 1026
fitted from truncated models 453
@identity 913
Index functions
Identity matrix 913
matrix first non-missing 744
extract column 1169
matrix last non-missing 745
if 349
series first non-NA 914
If statement 157
series last non-NA 915
else clause 158, 347
vector first non-NA 914
end of condition 348
L—1245

vector last non-NA 915 K


Indicator functions 320
Kao panel cointegration test 400
INI file
K-class 503
replace from existing location 531
estimation of 503
save to new location 530
Kernel
Ini file
cointegrating regression 404, 406, 407
load key 945
GMM estimation 470
save key 583
robust standard errors 377, 385, 512, 610
Initial parameter values 564
Keyboard focus
@inlist 320, 921
defaults 17
@inner 922
KPSS unit root test 619
Inner product 922
@kronecker 935
INSEE (National Institute of Statistics and Economic
Kronecker product 935
Studies) 429
@kurt 936
@insert 94, 923
Kurtosis 936
Insertion point
by category 937
in command line 5
@kurtsby 937
@instr 91, 924
Kwiatkowski, Phillips, Schmidt, and Shin test 619
Instrumental variable 607, 612
Integer random number 576
L
Interactive mode 5
Intercept Lag
specify as range 354
matrix columns 747 @lag 939
@intercept 925 Lag operator 939
Intraday data Lagrange multiplier
date functions 122 test for serial correlation 381
@inv 865, 925 Landscape printing 23
@inverse 926 Lasso 625
Inverse of matrix 926 @last 593, 915, 940
element by element 865 Last non-missing
@isempty 91, 926 matrix columns 748
@isobject 929 matrix columns index 745
@ispanel 305, 929 vector or series 940
@isperiod 310, 930 vector or series index 915
@issingular 931 @lasterrnum 941
@isvalidgroup 931 @lasterrstr 942
@isvalidname 932 @lastmax 593
Iterate to convergence GMM @lastmin 593
single equation 468 Least squares
Iteration 511 variable selection 625
optimization method 511 @left 92, 942
@len 943
J Length
of string 1132
Jarque-Bera statistic 477
@length 90, 944
Johansen cointegration test 395
Length of string 943, 944
Jupyter notebook 205
Less than comparison 296
Justification 59, 63
1246—Index

matrix element by element 867 Logit models 382, 506


Less than or equal to comparison 296 logmode 506
matrix element by element 866 logmsg 509
Levin, Lin and Chu 619 logsave 509
Limited information maximum likelihood (LIML) @logx 951
See LIML Loop
LIML 503 exit loop 166, 348
estimation of 503 for 349
liml 503 for (control variables) 160
Line break (programs) 130 for (scalars) 162
Line numbers for (string variables) 162
in program 130 if 349
Linear nest 161
frequency conversion method 414 over matrix elements 161, 303
@linepath 944 while 160, 164, 355
Link Lotus file 640, 656, 666
convert to ordinary series 561, 618, 664 export data to file 656, 666
Litterman open 640
frequency conversion method 414 @lower 95, 951
Load Lower triangular matrix 951
workfile 640 Lowercase 951
@loadprgini 945 ls 474, 510
Local @ltrim 95, 953
samples 177 @lu 954
subroutine 175 LU Decomposition 954
variable 173
Log 152 M
See Logarithm.
ma 326
@log 947
MA specification 326
log 947 seasonal 329
Log window 152 Macro-recording 3
@log10 948 @mae 959
log1mexp 948 Magellan 429
log1p 949 Main diagonal 895
@log2pi 949 @makedate 116, 960
Logarithm @makediagonal 961
arbitrary base 951
@makevalidname 962
base-10 948
@mape 963
difference 842
Markov switching 602
natural 947
Matlab 196
natural,1 minus exponential of 948
matplace 518
natural,plus 1 949
Matrix 1147
logclear 504, 505
assign values 280
logeval 506
Cholesky factorization 743
Logistic
column product 771
logit function 950
column quantiles 771
@logit 950
column standard deviation 772, 773
logit 506
column trimmed mean 776
M—1247

column variance 807, 808 permute rows of 1037


columns, number of 759, 762 permute rows of using vector of ranks 733, 758
condition number 763 place submatrix 518
convert to/from series or group 290 place vector in column 410
copy 285 place vector into 581
covert from series or group (drop NAs) 598, 764 QR decomposition 1055
covert from series or group (keep NAs) 599 quadratic form 1049
covert from table 617 random normal 523, 574, 982
cumulative product 754 random uniform 575, 1000
cumulative sum 755 rank 1063
declare 279 ranks of the elements of the matrix 1064
demean columns 756 resample rows from 1071
detrend columns 757 reverse sweep operator 1097
element division 861, 869 rows, numbers of 1090
element equality 861, 862 rows, sort 1091
element greater than 863 scale rows or columns 1108
element greater than or equal to 863 singular value decomposition 1137, 1139
element inequality 870, 871 stack columns 1183
element inverse 865 stack lower triangular columns 1184
element less than 867 standardize (population)
element less than or equal to 866 columns 761
element maximum 868 standardize columns of matrix 760
element minimum 868 submatrix 287
element missing value 865 submatrix assign 290
element not missing value 872 subtract submatrix 1133
element power 873 sweep operator 1140
element recode 876 trace 1147
elementwise operations 298 trend coef for columns 775
export data 303 unique values 1169
extract row 1089, 1090 upper triangular 1171
fill values 884 vertical concatenation 1182
fill with values 281 views 301
generalized inverse 1038 Matrix commands and functions
import data 302 column means 304
increment rows or columns 920 column scaling 304
initialize to matrix 282 column summaries 299
initialize to scalar 282 commands 300
initialize using compatible matrix 282 descriptive statistics 299
initialize using creation functions 283 difference 299
initialize using function 283 element 297
lower triangular 951 functions 299
main diagonal 895 matrix algebra 298
norm 1012 missing values 300
objects 279 utility 297, 361
of ones 1018 Matrix concatenation 899
of zeros 1225 Matrix operators
outer product 1021 addition (+) 294
percentiles 758 and loop operators 303
permute columns of using vector of ranks 1065 comparison operators 296
1248—Index

division (/) 296 @mid 93, 974


multiplication (*) 295 MIDAS
negation (-) 294 regression 519
order of evaluation 294 Minimization
subtraction (-) 295 See also Optimization (user-defined).
@max 965 Minimization See Optimization (user-defined).
@maxerrs 966 Minimum
@maxes 966, 975 backwards cumulative 779
Maximization by category 977
See also Optimization (user-defined). cumulative 795
Maximization See Optimization (user-defined). index 918
Maximum 965 matrix columns 752
backwards cumulative 777 matrix columns index 746
by category 967 matrix element by element 868
cumulative 793 n-smallest number indices 918
index 916 n-smallest numbers 976
matrix columns 750 @mins 976
matrix columns index 746 @minsby 977
matrix element by element 868 @minute 123, 309
n-largest number indices 917 Minute of hour 978
n-largest numbers 966, 975 @minuter 978
Maximum likelihood Missing value comparison
See also Optimization (user-defined). matrix element by element 865
@maxsby 967 Missing values 300
Mean 971 code for missing 327
backwards cumulative 777 number of 1009
by category 972 recoding 1009
cumulative 794 Mixed data sampling
geometric 896 regression 519
harmonic 900 @mod 983
matrix columns 751 Mode 152
trimmed 1154 Model selection
@mean 971 TAR estimation 608
Mean absolute error 959 Models
Mean absolute percentage error 963 solve 594
Mean square error 1000 Modulus 983
@meansby 972 @month 122, 309, 593, 983
Median 973 Month of year 983
backwards cumulative 778 Moody’s Economy.com 429
by category 973 Moore-Penrose inverse of matrix 1038
Cumulative 794 Moving average (ARMA) 326
matrix columns 751 @mse 1000
@median 973 mtos 522
@mediansby 973 Multiplication 1042
Merge Multiplication operator (*) 295
graphs 37
panel data 416 N
Meta data
See Attributes na 327
O—1249

Name Number of periods


get next available object name 895 annuity 1013
make a valid object name 962 Numbers
test for valid object name 932 converting from strings 90, 1175
@nan 1009 formatting in tables 59
NAs formatting in tables See also Display format
comparisons 191
testing 191 O
@nas 1009
Object
NAs, number of
backwards cumulative 780 _this type 896
by category 1010 active type 896
cumulative 796 active 230
matrix columns 752 assignment 19
@nasby 1010 command 21
National Oceanic and Atmospheric Administration containers 27
430 copy 30, 411
Negation operator (-) 294 create using freeze 457
Negative binomial count model 419 declaration 21
@neqna 92, 1010 delete 31, 432
Newey-West automatic bandwidth fetch from database or databank 32, 449
cointegrating regression 404, 407 get next available object name 895
robust standard errors 377, 386, 512, 610 make a valid name 962
Newton’s method 272 output display 231
Newton-Raphson 511 placeholder 230
next 350 preview 564
@ngroups 702 print 566
NOAA 430 rename 31, 573
Nonlinear least squares save 32
single equation estimation 510, 519 store 32, 600
var estimation 474 test for existence 929
Non-missing value comparison test for valid name 932
matrix element by element 872 @obs 1015
@norm 1012 @obsby 1016
Norm of a matrix 1012 Observation
Normal distribution identifier series 1026
random number 523, 574, 982 Observations
Normality test 477 number in workfile 1017
Not equal to comparison 296 Observations, number of 1015
matrix element by element 870, 871 backwards cumulative 780
@now 122, 1013 by category 1016
Nowcasting 519 cumulative 797
@npers 1013 matrix columns 754
nrnd 523 @obsid 320, 1016
N-step GMM @obsnum 305
single equation 468 @obsrange 305, 1017
Number format @obssmpl 306, 1017
See Display format ODBC 640
1250—Index

OECD 430 replace 531


OLEDB Driver 194 save to new location 530
OLS (ordinary least squares) Options
single equation estimation 510 in programs 156
var estimation 474 @optiter 267
variable selection 625 @optmessage 267
Omitted variables test 606 Optmization (user-defined)
OneDrive 389, 644, 662 optsave 530
@ones 1018 optset 531
Ones matrix 1018 @optstatus 267
One-step GMM or 682
single equation 468 Order of evaluation 294
Open ordered 532
database 424, 428 Ordered dependent variable
foreign data as matrix 489 estimating models with 532
foreign data as table 496 @otod 100, 1019
foreign source data 480, 640 @otods 100, 1020
text or program files 524 @outer 1021
workfile 640 Outer product 1021
open 524 Output
Operator display estimation results 533
relational 87 printing 23
Optimization redirection 350, 351, 533
methods 511 output 533
Optimization (user-defined) 261
analytical gradients 264, 527 P
controls 261, 525
Page
examples 267
check for existence of 306
gradients 264, 527
contract 537
Hessian 265, 527, 528
copy from 538
least squares 263
create new 540
maximization 263
define structure 558
maximum likelihood 263
delete page 546, 547, 656
method 263
frequency 1025
minimization 263
frequency of 306
numeric derivatives 265
name of active 1029
objective 261, 525
number in workfile 1024
parameters 261, 525
number of 306
starting values 264
observation identifier series 1026
status messages 267
observation index vector 1027, 1028
step method 266, 275
order 655
technical details 272
range specification 1029
termination 276
rename 548
Optimization algorithms
resize 558
Gauss-Newton 511
retrieve current sample 306
Newton-Raphson 511
retrieve ID series 306
optimize 261, 263, 525
retrieve name of 306
@option 1019
retrieve names of 306
Option settings
P—1251

sample index vector 1030 param 564


sample specification 1030 Parameters 564
save or export 548 PARCH 369
set active 554 Partial covariance analysis 421
sorting 595 Parzen kernel
stack 555 cointegrating regression 404, 406, 407
subset from 537 GMM estimation 470
test for existence 1024 robust standard errors 377, 385, 512, 610
pageappend 536 Parzen-Cauchy kernel
pagecontract 537 cointegrating regression 404, 406, 407
pagecopy 538 GMM estimation 470
@pagecount 306, 1024 robust standard errors 377, 385, 512, 610
pagecreate 540 Parzen-Geometric kernel
pagedelete 546, 547, 656 cointegrating regression 404, 406, 407
@pageexist 306, 1024 GMM estimation 470
@pagefreq 306, 1025 robust standard errors 377, 385, 512, 610
@pageid 306 Parzen-Riesz kernel
@pageids 1026 cointegrating regression 404, 406, 407
@pageidx 1027, 1028 GMM estimation 470
@pagelist 306 robust standard errors 377, 385, 512, 610
pageload 546 Path
@pagename 306, 1029 default workfile 1198
@pagerange 1029 retrieve workfile path 306
pagerename 548 Payment amount 1040
pagesave 548 @pc 1031
pageselect 554 @pca 1031
@pagesmpl 306, 1030 @pccagr 1032
@pagesmplidx 1030 @pch 1033
pagestack 555 @pcha 1033
pagestruct 558 @pchy 1034
pageunlink 561 @pctiles 758
pageunstack 562 @pcy 1036
@paglist 1028 pdl 328
Pairwise maximum 1039 PDL (polynomial distributed lag) 328
Pairwise minimum 1039 Pearson correlation
Panel from group 418
test workfile 929 Pearson covariance 421
Panel data Pedroni panel cointegration test 400
cell identifier 320 Percent change
functions 320 one-period 1031, 1033
group identifier 320 one-period annualized 1031, 1033
time trend 321 one-year 1034, 1036
trends 320 Percentiles 758
unit root tests 619 Period
within-group identifier 320 dummy variable 310
workfile structure 305 Period-to-date 1036
Panel workfile @periodtodate 1036
functions 320 Permute
1252—Index

columns of a matrix using vector of ranks 1065 Program


rows of a matrix using vector of ranks 733, 758 abort 136
rows of matrix 1037 arguments 151, 155, 156
@permute 1037 backup files 131
Phillips-Perron test 619 basics 129
Pi 1037 break 136
logarithm of 2 times 949 call subroutine 171, 347
@pi 1037 clearing execution errors 393
@pinverse 1038 command capture 410
plot 564 counting execution errors 877
@pmax 1039 create 129
@pmin 1039 create new file 567
@pmt 1040 debugging 137
poff 350 dependencies 139
Point encrypt 133
frequency conversion method 414 equals option 875
Poisson count model 419 errors 165
pon 351 example 141
Pool exec 444
identifier comparison with “?” wildcard 1230 execution 133
Portrait (print orientation) 23 execution error code 941
@pow 1041 execution error string 942
exit loop 166
@pow1pm1 1041
file location 1101
Power 1041, 1042
for 160
Power (raise to)
if 157
matrix element by element 873
if statement 157
@powm1 1042
include file 168, 349
Precedence of evaluation 294
ini file 583, 945
Present value 1044
line comment character 130, 142
preview 564
line continuation character 130
Print
line numbers 130
and display 23
location of file 944
automatic printing 350, 351
log See Program log.
landscape 23
maximum execution errors 966
portrait 23
maximum number of execution errors 588
spool by command 82
modes 151
tables by command 73
multiple programs 167
turn off in program 350
number of execution errors 587
print 566
open 133
probit 567 option 899, 1019
Probit models 382 Options 156
Procedures place subroutine 172
documentation 476 run 581
@prod 1042 running 133
Product 1042 save 131, 133
backwards cumulative 781 snapshots 131
cumulative 797 stop 136, 166
matrix columns 771 stop execution 353
R—1253

string object 101, 146 R


strings 101, 145
R 197
user-defined dialogs 178
R project 197
variables 143
Ramsey RESET test 574
version 4 compatibility 152, 192
Random number
while 164
generator for normal 523, 574, 982
program 567
generator for uniform 575, 1000
Program evaluation 434
integer 576
Program log 152
seed 577
add message 509
@range 1063
clear 504, 505
range 570
save 509
Range of integers 1063
send to log 506
@rank 1063
set log settings 506
Rank (matrix) 1063
Programming language command entries 347
@ranks 1064
Programming See Program.
@rate 1066
Pseudoinverse 1038
Rate for annuity 1066
@psi 839, 1043
RATS data
@pv 1044
importing 480
Python 202
open 640
Read 480, 489, 496, 640
Q
data from foreign file 480, 570
@qform 1049 data from foreign file as matrix 489
@qr 1055 data from foreign file as table 496
QR decomposition 1055 read 570
qreg 567 Reading EViews data (in other applications) 193
Quadratic Recession shading 217
frequency conversion method 414 Reciprocal 925
Quadratic form 1049 Recode
Quadratic spectral kernel matrix element by element 876
cointegrating regression 404, 406, 407 @recode 1068
GMM estimation 470 Recode values 915, 1068
robust standard errors 377, 385, 512, 610 Recording user actions 3
Quantile Redirect output to file 23, 533
backwards cumulative 782 Redundant variables test 607
by category 1058 @regress 1069
Cumulative 798 Regression
matrix columns 771 breakpoint estimation 384
@quantile 1057 regression 1069
Quantile function 1057 Remainder
Quantile method 1057 floating point 983
Quantile regression 567 Rename
@quantilesby 1058 database 432
Quarter 1059 object 31, 573
@quarter 122, 309, 593, 1059 page 548
Query workfile page 548
database 1209 rename 573
Quiet mode 151 Reorder
1254—Index

columns of a matrix using vector of ranks 1065 extract from matrix 1089, 1090
rows of a matrix 1037 filled rowvector function 885
rows of a matrix using vector of ranks 733, 758 @rrinstr 1078
@replace 94, 1070 @rsweep 1097
Replacement variable 147 RTF 73
naming objects 148 @rtrim 95, 1100
Resample run 444, 581
rows from matrix 1071 Run program 444, 581
@resample 1071 application in batch mode 136
reset 574 multiple files 167
RESET test 574 runpath 1101
Reset timer 611
Reshaping a workfile 558 S
Resize
Sample
page 558
@all 593
Restructuring 558 all observations 593
return 351 change using for loop 161
Reverse sweep operator 1097 @day 593
Rich Text Format earliest of first panel obs 593
See RTF. earliest of last panel obs 593
@right 93, 1075 @first 593
@rmse 1084 first observation 593
rmvnorm 574 @hour 593
rnd 575 @hourf 593
rndint 576 index vector 1030
rndseed 577 @last 593
Robust least squares 578 last observation 593
Robust regression latest of first panel obs 593
See also Robust least squares. latest of last panel obs 593
robustls 578 local 177
Rolling regression @month 593
user object example 243 number of observations 1017
Root mean square error 1084 number of observations in 306
Round 1088 @quarter 593
upward 737 retrieve current default 306
@round 1088 set current 592
Round downward 887 @weekday 593
Roundoff error in for loops 352 @year 593
Row Samples
height 60 local 177
numbers 1090 sar 329
place in matrix 581 SAR specification 329
sort 1091 SARMA 329
@rowextract 1089, 1090 SAS file 640
rowplace 581 Save 656
@rows 99, 1090 commands in file 5
@rowsort 1091 objects to disk 32
Rowvector tables 73
S—1255

workfile 656 Shell 589


workfile as foreign file 656 shell 589
save 583 show 589
saveprgini 583 Show object view 589
Scalar @sign 1112
initialize matrix 282 Sign of number 1112
@scale 1108 @sin 1112
Scale rows or columns of matrix 1108 Sine 1112
SDMX_ML format 430 Singular matrix
@seas 310, 1109 test for 931
seas 584 Singular value decomposition 1137, 1139
Seasonal @skew 1113, 1114
ARMA terms 329 Skewness 1113, 1114
dummy variable 310 by category 1114
Seasonal adjustment @skewsby 1114
moving average 584 sleep 351
Seasonal dummy 1109 sma 329
@second 123, 310, 1109 smooth 590
Second of minute 1109 Smoothing
Seed random number generator 577 exponential smooth series 590
Selection model smpl 592
Heckman selection equation 474 Solve
@seq 1110 linear system 1115
@seqm 1111 simultaneous equations model 594
Sequence solve 594
arithmetic 897, 1110 @solvesystem 1115
multiplicative 1111 Sort
Sequential LR tests 166 vector 1116
Serial correlation workfile page 554, 595
Breusch-Godfrey LM test 381 @sort 1116
Series sort 595
auto-updating 458 spawn 596
convert to matrix 292, 522 Spawn process within EViews 596
convert to matrix (keep NAs) 599 Special expression command entries 323
descriptive statistics 597 Spool
extract observation 305 add objects 78
formula 458 add objects by command 78
preview 564 comments by command 81
smoothing 590 create by command 77
unique values 1169 display name 80
setcell 585 display name by command 80
setcolwidth 586 extract by command 81
seterrcount 587 naming objects by command 80
setline 588 object comments 81
setmaxerrs 588 object names 80
@sfill 1111 print by command 82
Shade region of graph removing objects 81
by command 51 Spreadsheet
1256—Index

file export 656 Store


file import 480, 640 object in database or databank 32, 600
file import as matrix 489 store 600
file import as table 496 @str 98, 1123
SPSS file 640 @strdate 99, 123, 310, 1128
sqr 1116 String 85
@sqrt 1117 add quotes 96, 715
Square root 1116, 1117 as replacement variable 147
Stability test assign to table cell 58
Chow breakpoint 392 change case 95
factor 446 comparison 87
Stack concatenation 86
matrix by column 1183 convert date string to observation 100
sym matrix by lower column triangle 1184 convert date value into 824
workfile page 555 convert date value to string 115
Standard deviation convert from a number 1123
backwards cumulative 783, 784, 785 convert into date value 825
by category 1119, 1120 convert number to string 98
cumulative 799, 800, 801 convert to date number 98, 115
matrix columns 772, 773 convert to number 99, 146, 1175
population 1118 convert to numbers 90
sample 1117, 1119 current date as a string 100
Standardize 760, 1121 extract portion 92, 93
population 1122 find substring 91, 924
matrix columns 761 find substring from end 1078
Starting values 564 for loop 162
user defined optimization 264 functions 90
Stata file 640 in programs 145
Static forecast 452 insert string into another string 94, 923
Statistics Canada 430 insert string into another string at word 1199
stats left substring 942
series 597 length 90, 943, 944, 1132
Status line 598 lowercase 951
statusline 598 missing value 85, 88
@stdev 1117 null string 85
@stdevp 1118 operators 86
@stdevpsby 1119 ordering 87
@stdevs 1119 program arguments 151, 155, 156
@stdevsby 1120 relational comparison 87
relational comparisons with empty strings 88
@stdevssby 1120
replace portion of a string with new string 94,
@stdize 1121
1070
@stdizep 1122
right substring 1075
step 352
string lists 89
Stepwise regression 625
strip commas 1129
stom 598
strip parentheses from ends 96, 1130
stomna 599
strip quotes from ends 96, 1131
stop 353
substring from location 974
Stop program execution 136, 166, 353
test for blank 91
S—1257

test for empty string 926 Submatrix 287


test for equality 873, 927 assign 290
test for inequality 1010 Subroutine 168
test for missing 926 arguments 169
test two strings for equality 91 call 171, 347
test two strings for inequality 92 declare 353
trim spaces 95 define 168
trim spaces from ends 95, 1153 global 173
trim spaces from left end 953 local 175
trim spaces from right end 1100 mark end 348
uppercase 1171 optimization 261
variable 101, 145 placement 172
vectors 102 return from 169, 351
String (variable) 101 subroutine 353
String list Substring 93, 924, 974, 1078, 1206
compare strings 96, 1207 Subtraction operator (-) 295
count 90, 1188 Sum 1135
create from svector 99, 1202 backwards cumulative 786
create svector 99, 1216 by category 1136
cross lists 97, 1188 cumulative 802
delimiters 97, 1189 cumulative sum of negative (below threshold) dif-
drop string 94, 1191 ferences 790
extract string 94, 1202 cumulative sum of positive (above threshold) dif-
find element 94, 1208, 1209 ferences 791
find last string 1213 cumulative sum of zero (at threshold) differences
find last string word 1212 792
find string 91, 1196, 1197 difference of the cumulative sum of negative
interleave lists 97, 1200 (below threshold) differences 831
intersect strings 96, 1201 difference of the cumulative sum of positive
left substring 93, 1203 (above threshold) differences 832
replace string 95, 1211 difference of the cumulative sum of zero (at
right substring 93, 1214 threshold) differences 833
sort 97, 1215 matrix columns 774
substring from location 93, 1206 @sum 1135
union of strings 96, 1216 Sum of squared values
unique string 96, 1217 backwards cumulative 786
String object 101, 146 cumulative 803
String vector 102 Sum of squares 1136
row count 99 by category 1137
@stripparens 96, 1130 matrix columns 774
@strippcommas 1129 @sumsby 1136
@stripquotes 96, 1131 @sumsq 1136
@strlen 1132 @sumsqby 1137
@strnow 100, 1132 @svd 1137, 1139
Structural change Svector
See also Breakpoint test. create from string list 99
estimation in the presence of 384 create from strings 1111
Structuring a workfile 558 create string list 99, 1202
@subextract 1133 @sweep 1140
1258—Index

Sweep operator 1140 TARCH


reverse 1097 See ARCH.
Switching regression 602 Template
switchreg 602 by command 51
Sym @temppath 1145
create from lower triangle of square matrix 919 Test
create from scalar function 885 Chow 392
create from upper triangle of square matrix 920 for equality of matrix values 861, 862
create square matrix from 880 for inequality of matrix values 870, 871
lower triangular matrix 951 for serial correlation 381
scale rows and columns 1108 Granger causality 387
stack columns 1184 Johansen cointegration 395
upper triangular 1171 omitted variables 606
redundant variables 607
T RESET 574
unit root 619
Table
testadd 606
assigning numbers to cells 58
testdrop 607
assigning strings to cells 58
assignment with formatting 59 Text file
background color 65 import 480
borders and lines 65 import as matrix 489
cell format 62 import as table 496
cells 68 open as workfile 640
conditional cell selectoin 68 save workfile as 656
convert from matrix 617 @theil 1035, 1145
copy table to new table 605 Theil inequality coefficient 1035, 1145
create using freeze 457 then 353
creating 57 tic 611
creating by freezing a view 57 Time
customization 74 current 1146
decimal format code 59 current as string 1132
declare 58 @time 1146
export 73 Time trend 1148
find cell with contents 72 Time trend (calendar) 1150
font 64 Time trend with break 1149
horizontal line 588 Timer 611, 1146
insert table in new table 605 to 354
print 73 Tobit 389
row heights 60 @toc 1146
save to disk 73, 583 toc 611
set and format cell contents 585 TOC ini 227, 255
set column width See Column width. Trace
text color for cells 64 of matrix 1147
write to file 73 @trace 1147
@tablenames 1143 Trading Economics 430
tabplace 605 Transpose
@tan 1144 matrix 1147
Tangent 1144 @transpose 1147
U—1259

Trend unique values 1169


coefficient from regression 775, 1151 @uniquevals 1169
intercept from trend regression 925 Unit root test 619
panel functions 320 Elliot, Rothenberg, and Stock 620
@trend 310, 321, 1148 KPSS 619
in panel 321 Unit vector 1169
@trendbr 1149 @unitvector 1169
@trendc 310, 321, 1150 unlink 618
@trendcoef 1151 Unstack
@trigamma 1152 vector into matrix 1170
@trim 95, 1153 vector into sym matrix 1171
Trimmed mean 1154 Unstacking data 562
matrix columns 776 Untitled 26
@trmean 1154 @unvec 1170
Truncated dependent variable 389 @unvech 1171
tsls UOPZ file 254
single equation 607, 612 @upper 95, 1171
TSP portable data format 430 Upper triangular matrix 1171
ttom 617 Uppercase 1171
Tukey 1057 uroot 619
Tukey-Hamming kernel US Census 430
cointegrating regression 404, 406, 407 User defined menus
GMM estimation 470 See Add-ins.
robust standard errors 377, 385, 512, 610 User interface 178
Tukey-Hanning kernel dialog 184, 1159
cointegrating regression 404, 406, 407 edit 180, 1162
GMM estimation 470 file dilaog 186, 1163
robust standard errors 377, 385, 512, 610 listbox 181, 1164
Tukey-Parzen kernel multiple-list box 182, 1165
cointegrating regression 404, 406, 407 prompt 179, 1166
GMM estimation 470 radio button 183, 1168
robust standard errors 377, 385, 512, 610 User objects 233
Two-stage least squares adding 253
See 2sls (Two-Stage Least Squares). creation 254
data members 235
U definition 233
definition file 252
U.S. Energy Administration 429
downloading 236
@uidialog 184, 1159
examples 239
@uiedit 180, 1162
installer 256
@uifiledlg 186, 1163
installing 238
@uilist 181, 1164, 1165
management 249
@uimlist 182
register 367
@uiprompt 179, 1166
registered 236
@uiradio 183, 1168
registration 253
UN 430
TOC ini 255
Uniform distribution unregistered 234
random number 575, 1000 using 234
Unique values 1169
1260—Index

User-defined dialogs 178 unstack into matrix 1170


User-defined optimization unstack into sym matrix 1171
See Optimization (user-defined). Verbose mode 151
@vernum 1184
V Version number 1184
@val 99, 1175 @verstr 1184
Values Vertical matrix concatenation 1182
number of matching@cvalcount 806
number of matching@valcount 1178 W
Van der Waerden 1057 Watch window 137
VAR @wcount 90, 1188
estimation 624 @wcross 97, 1188
@var 1179 @wdelim 97, 1189
Variable @wdir 100, 1190
program 143 @wdrop 94, 1191
Variable selection 625 @weekday 122, 309, 593, 1192
auto-search/GETS 625 wend 354
Lasso 625 @wexpand 1192
Variance @wfattrnames 1194
backwards cumulative 787, 788, 789 @wfattrvals 1195
by category 1180, 1181, 1182 wfclose 631
cumulative 803, 804, 805 wfcompare 632
matrix columns 807, 808 wfcreate 634
populatioin 1179 wfdetails 638
population 1179 wfdir 639
sample 1181 wffilter 639
Variance equation @wfind 91, 1196
See ARCH and GARCH. @wfindnc 1197
@varp 1179 @wfname 306, 1198
@varpsby 1180 wfopen 640
@vars 1181 wforder 655
@varsby 1181 @wfpath 306, 1198
varsel 625 wfsave 656
@varssby 1182 wfselect 663
@vcat 1182 wfsnapshot 663
VEC wfstats 664
estimating 624 wfunlink 664
@vec 1183 wfuse 665
@vech 1184 while 355
Vector 1169 While loop 164
fill 884 abort 165
fill values 886 end of 354
grid 897, 1110 exit loop 166
integer range 1063 start of 355
outer product 1021 WHO 430
ranks of the elements of the matrix 1064
Wildcard characters 30, 1227
sequence 897, 1110
Windmeijer standard errors 470
unit 1169
Window
X—1261

docking and moving 10 panel structured 305


Windows panel to pool 562
command shell 596 period indicators 310
Windows shell 589 pool to panel 555
@winsert 1199 rename page 548
@winterleave 97, 1200 retrieve name of 306
@wintersect 96, 1201 retrieve path of 306
@wjoin 99, 1202 save 28, 656
@wkeep 94, 1202 save individual page 548
@wleft 93, 1203 seasonal indicators 310
@wlookup 100, 1204 set active workfile and page 554, 663
@wmid 93, 1206 snapshot 663
@wnotin 96, 1207 sorting 595
@word 94, 1208 stacking 555
@wordq 94, 1209 start date of observation interval 308
Workfile 27, 558 time trend 310, 321
activate 665 time trend (calendar based) 310
append to 536 unstacking 562
attributes 487, 638 workfile 666
close 28, 631 World Bank 430
comparing 632 World Health Organization 430
contract 537 @wquery 1209
convert repeated obs to repeated series 562 Wrapping text 129
convert repeated series to repeated obs 555 @wreplace 95, 1211
copy from 538 @wrfind 1212
create 422, 634 @wrfindnc 1213
create page in 540 @wright 93, 1214
date strings 99, 123, 310 Write
define structured page 558 data to text file 666
delete page 546, 547, 656 write 666
details 638 @wsort 97, 1215
directory 639 @wsplit 99, 1216
display statistics view 664 @wunion 96, 1216
end date of observation interval 308 @wunique 96, 1217
export 656
filter display 639 X
find objects 100, 1204
xclose 668
frequency 27
xget 668
functions 305, 696
xlog 671
import 480
xoff 671
import foreign source into 480
xon 672
information 305
xopen 672
load workfile pages into 546
number of observations in 305 xpackage 674
observation date functions 122, 309 xput 675
observation numbers 305 @xputnames 1220
open existing 28, 640 xrun 677
open foreign source into 640
order 655
1262—Index

Y
Year 1192
@year 122, 309, 593, 1192
Year-to-date 1223
@ytd 1223

Z
@zeros 1225
Zeros matrix 1225

You might also like