# [Numpy-discussion] Time series: lag function

Vincent Nijs v-nijs at kellogg.northwestern.edu
Wed Dec 27 19:01:55 CST 2006

```Sven:

I simplified the function to create lags only along axis 0 (see attached). I
am using c_ now which seems to play nice with 1- and 2-d array's.

The reason I am using 'n = ravel(n)' in the code is that I want to be able
to pass integers as well as lists. For example, I want each of the following
to work:

lag(a,2)
lag(a,range(1,3))
lag(a,[1]+range(4,6))

I'd actually also like the following to work:

lag(a,1,3,6,8)

I could do that with *n but then I don't think I can use range(x,y) in the
same function call. For example, lag(a,1,3,range(6,9)).

You probably don't need this flexibility when calling diff() since, at least
in TS applications, I only ever need diff(a,1) or diff(a,2).

Thanks,

Vincent

On 12/27/06 6:17 PM, "Sven Schreiber" <svetosch at gmx.net> wrote:

> Vincent Nijs schrieb:
>> I am  tryin to convert some of my time-series code written in Ox to
>> scipy/numpy (e.g., unit root tests, IRFs, cointegration, etc). Two key
>> functions I need for this are 'lag' and 'diff'. 'diff' is available but
>> 'lag' is apparently not.
>>
>> Below is my attempt at a lag function. I tried to be somewhat consistent
>> with the diff function which is part of numpy (also listed for convenience).
>> It seems to work fine for a 2-d array but not for a 1-d or 3-d array (see
>> tests at bottom of email). I'd appreciate any suggestions you may have.
>>
>
> Great to see somebody converting from Ox to numpy, I see synergies ahead!
>
>
>> def lag(a, n=1, lag_axis=0, concat_axis=1):
>>     """
>>     Calculate the nth order discrete lag along given axis.
>>     Note: axis=-1 means 'last dimension'. This is the default
>>     for the diff function. However, the first dimension (0)
>>     may be preferred for time-series analysis.
>>     """
>>     a = asanyarray(a)
>>
>>     n = ravel(n)                # convert input to an array
>
> why don't you leave n as an integer? maybe you're trying to be too
> clever here. I think it's a good idea to have lag resemble the existing
> diff function, and then a single number n should be enough.
>
> (And I'm not sure about your concat_axis, e.g. what does axis=1 mean for
> a 1-d array?)
>
> Do you get your errors also for integer n?
>
> cheers,
> sven
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion at scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>

--

-------------- next part --------------
A non-text attachment was scrubbed...
Name: lag.py
Type: application/octet-stream
Size: 479 bytes
Desc: not available
Url : http://projects.scipy.org/pipermail/numpy-discussion/attachments/20061227/d38b4c5e/attachment.obj
```