Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views3 pages

MLT Final

This document outlines an algorithm to implement XGBoost for stock price prediction using Tesla stock data. The algorithm reads in CSV data, splits it into training and test sets, trains an XGBoost regressor on the training set and makes predictions on the test set, and calculates evaluation metrics to analyze the model's performance.

Uploaded by

shrihari.9919an
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

MLT Final

This document outlines an algorithm to implement XGBoost for stock price prediction using Tesla stock data. The algorithm reads in CSV data, splits it into training and test sets, trains an XGBoost regressor on the training set and makes predictions on the test set, and calculates evaluation metrics to analyze the model's performance.

Uploaded by

shrihari.9919an
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

CS22412 – ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

LABORATORY

EX.NO:11
DATE:

XGBOOST

AIM:
To implement XG Boost for sales spice prediction.
ALGORITHM:
1. Start
2. Read the Tesla stock data from a CSV file into a DataFrame (df).
3. Plot the close price of Tesla stock over time using matplotlib.
4. Display histograms for each feature ('Open', 'High', 'Low', 'Close', 'Volume') using seaborn.
5. Split the 'Date' column into year, month, and day components and add them as new columns
in the DataFrame.
6. Make a copy of the DataFrame (data).
7. Define features (X) and target variable (y).
8. Split the data into training and testing sets using train_test_split.
9. Initialize an XGBoost regressor (xgb).
10. Train the XGBoost model on the training data.
11. Make predictions on the testing data.
12. Calculate the root mean squared error (RMSE) between the actual and predicted values.
13. Plot the actual vs predicted stock prices using matplotlib.
14. Stop

ROLL NO: 2127220501140 Page | 45


PROGRAM:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error

df = pd.read_csv('/content/TSLA (1).csv')
plt.plot(df['Close'])
plt.title('Tesla close price')
plt.ylabel('Price in USD')
plt.show()
df.head()

features = ['Open','High','Low','Close','Volume']

for i,col in enumerate(features):


sb.distplot(df[col])
plt.show()
splitted = df['Date'].str.split('-',expand = True)
df['year'] = splitted[0].astype('int')
df['month'] = splitted[1].astype('int')
df['day'] = splitted[2].astype('int')
df.head()

data = df.copy()

X = data[['Open', 'High', 'Low', 'Close', 'Volume']]


y = data['Close']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

xgb = XGBRegressor(objective='reg:squarederror', random_state=42)

xgb.fit(X_train, y_train)

y_pred = xgb.predict(X_test)

rmse = np.sqrt(mean_squared_error(y_test, y_pred))


print("Root Mean Squared Error:", rmse)
plt.figure(figsize=(10, 6))
plt.plot(y_test.values, label='Actual')
plt.plot(y_pred, label='Predicted')
plt.title('Tesla Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('Stock Price')
plt.legend()
plt.show()
ROLL NO: 2127220501140 Page | 46
SAMPLE INPUT/OUTPUT:

RESULT:
Hence program to predict tesla stock price using XGBoost gradient boosting has been
executed successfully and predictions has been visualized.

ROLL NO: 2127220501140 Page | 47

You might also like