Saturday, April 10, 2010

Python, Econometrics: Creating a lag matrix

I have not touched time series topics much in my introductory Econometric 131. Today we will start to create functions which we believe will be useful for time series studies.The first one is to create a lag matrix.

Consider the vector X whose elements are
X = [3,6,4,1,0, -1, 2,7]

and let us write a matrix built from X with lags added. One could build the lag matrix suche that the
last element of X is an element of the vector with zero lag or in another way, include the first element
of X in the vector with zero lag.

The first style would look like as follows:

Y: lag= 0: X[2],...,X[7]
X1: lag= 1: X[1]..., X[6]
X2: lag= 2: X[0],.., X[5]

The vector with lag of 1 would be $X_{-1}$ or as $X_{i-1}$. The the second style would look like

Y: lag= 0: X[0],.., X[5]
X1: lag= 1: X[1]..., X[6]
X2: lag= 2: X[2],...,X[7]

and the vector with lag of 1 would be denote $X_{1}$ or as $X_{i+1}$.

The following function would generate a lag matrix from the vectors $X_{minlag}$ to $X_{maxlag}$.

def makelagmatrix(X, minlag=0, maxlag= 2, style=[0,1][0]):
L=[]
n = len(X)
if style==0:
for i in range(0,n-maxlag):
row = [X[i+j] for j in range(minlag, maxlag+1)]
L.append(row)
else:
for i in range(maxlag,n):
row = [X[i-j] for j in range(minlag, maxlag+1)]
L.append(row)
return L

minlag = 1
maxlag = 2
X= [3,6,4,1, 0, -1,2,7]
print X

Y = X[:-maxlag+1]
matlib.mataugprint(makelagmatrix(X, minlag, maxlag), Y)

Y = X[maxlag:]
matlib.mataugprint(makelagmatrix(X, minlag, maxlag,1), Y)


When the above program runs it outputs:

[3, 6, 4, 1, 0, -1, 2, 7]
6.0000 4.0000 | 3.0000
4.0000 1.0000 | 6.0000
1.0000 0.0000 | 4.0000
0.0000 -1.0000 | 1.0000
-1.0000 2.0000 | 0.0000
2.0000 7.0000 | -1.0000

6.0000 3.0000 | 4.0000
4.0000 6.0000 | 1.0000
1.0000 4.0000 | 0.0000
0.0000 1.0000 | -1.0000
-1.0000 0.0000 | 2.0000
2.0000 -1.0000 | 7.0000