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]: ...
Get Mastering pandas for Finance now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.