Hyperparameter Tuning Using GridSearchCV

Lesson Overview

Welcome to today's lesson on Hyperparameter Tuning Using GridSearchCV! Our goal is to optimize a Gradient Boosting model to predict Tesla ($TSLA) stock prices more accurately. This lesson will guide you through the process of hyperparameter tuning using GridSearchCV, focusing on understanding key hyperparameters, setting up a hyperparameter grid, and implementing GridSearchCV to find the better model parameters.

Brief Revision of Loading and Preparing the Dataset

Before diving into hyperparameter tuning, let's quickly revise how we load and prepare our dataset. We start by loading the Tesla dataset, adding technical indicators, and splitting the data into training and testing sets.

Here's a quick overview of the code:

Python
import pandas as pd
from datasets import load_dataset

# Load dataset
tesla = load_dataset('codesignal/tsla-historic-prices')
tesla_df = pd.DataFrame(tesla['train'])

# Feature Engineering
tesla_df['SMA_5'] = tesla_df['Adj Close'].rolling(window=5).mean()
tesla_df['SMA_10'] = tesla_df['Adj Close'].rolling(window=10).mean()
tesla_df['EMA_5'] = tesla_df['Adj Close'].ewm(span=5, adjust=False).mean()
tesla_df['EMA_10'] = tesla_df['Adj Close'].ewm(span=10, adjust=False).mean()

# Drop NaN values created by moving averages
tesla_df.dropna(inplace=True)

# Select features and target
features = tesla_df[['Open', 'High', 'Low', 'Close', 'Volume', 'SMA_5', 'SMA_10', 'EMA_5', 'EMA_10']].values
target = tesla_df['Adj Close'].shift(-1).dropna().values  # Predicting next day's close price
features = features[:-1] # Align features and target arrays correctly for time series forecasting

# Splitting the dataset into training and testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.25, random_state=42)

The code above loads the Tesla historic prices dataset, applies feature engineering to add technical indicators like Simple Moving Averages (SMA) and Exponential Moving Averages (EMA), and preprocesses the dataset by removing NaN values. It then selects relevant features and the target variables, preparing the data for training and testing by splitting it into training and testing sets. The line target = tesla_df['Adj Close'].shift(-1).dropna().values is used for predicting the next day's closing price. The line features = features[:-1] ensures that the features and target arrays are aligned correctly for a time series forecasting task where you want to predict the next day's closing price.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal