This tutorial explains how to create lag variables in pandas using gold and silver price data from rdatasets.
The documentation for each package used in this tutorial is linked below:
The data is from rdatasets imported using the Python package statsmodels.
Create lag variables, using the shift function. shift(1) creates a lag of a single record, while shift(5) creates a lag of five records.
This creates a lag variable based on the prior observations, but shift can also take a time offset to specify the time to use in shift. For example, 1D and 5D can be used to lag by 1 and 5 days respectively.
First, a datetime index must be created from date.