O'Reilly logo

Mastering pandas for Finance by Michael Heydt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Shifting and lagging time-series data

A common operation on time-series data is to shift or "lag" the values back and forward in time, such as to calculate percentage change from sample to sample. The pandas method for this is .shift(), which will shift the values in the index by a specified number of units of the index's period.

To demonstrate shifting and lagging, we will use the adjusted close values for MSFT. As a refresher, the following command shows the first 10 items in that time-series:

In [29]:
   msftAC[:5]

Out[29]:
   Date
   2012-01-03    24.42183
   2012-01-04    24.99657
   2012-01-05    25.25201
   2012-01-06    25.64429
   2012-01-09    25.30675
   Name: Adj Close, dtype: float64

The following command shifts the adjusted closing prices forward by 1 day:

In [30]: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required