Creating Lag Features for Time Series Prediction
Lesson Overview
Hello! Today, we'll explore creating lag features for time series prediction using Tesla ($TSLA) stock data. Let's start by reviewing how to load the dataset and create basic features.
Reviewing Dataset and Basic Feature Creation
First, let's load the dataset and create new features based on existing columns such as High-Low and Price-Open.
Here, we calculate High-Low (the difference between the highest and lowest price of the day) and Price-Open (the difference between the closing and opening price) to create new features.
Introduction to Lag Features
Lag features are essential in time series prediction as they help capture temporal patterns in the data by generating new features from past values. Essentially, these features allow us to use past values to predict future ones.
For instance, predicting today's closing price of Tesla stock might depend on the previous day's closing price. Here, the previous day's closing price would be a lagged feature.
Creating and Implementing Lag Features
Let's see how to create lag features using the shift() method in Pandas. We will add a new column, Close_lag1, to capture the previous day’s closing price.
The output of the above code will be:
This output shows how the Close_lag1 column shifts the Close column values down by one row, making the first row's Close_lag1 value NaN because there is no previous row to shift from.
By using shift(1), we shift the closing price values down by one row, effectively capturing the previous day's closing price in a new column.
