Book Image

Mastering Pandas for Finance

By : Michael Heydt
Book Image

Mastering Pandas for Finance

By: Michael Heydt

Overview of this book

Table of Contents (16 chapters)
Mastering pandas for Finance
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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]:
   shifted_forward = msftAC.shift(1)
   shifted_forward[:5]

Out[30]:
   Date
   2012-01-03         NaN
   2012-01-04    24.42183
   2012-01-05    24.99657
   2012-01-06    25.25201
   2012-01-09    25.64429
   Name...