Apple Stock Price Prediction

Hidevs Community
24 min readOct 24, 2023

--

Objective: -

The goal of this challenge is to build a machine learning model that predicts the stock price of Apple company.

The September event of Apple is one of the favourite events for all Apple users, as iPhones are mainly launched during the September event. It is therefore announced by Apple that they are set to launch the new iPhone 14 on September 7. So many stock market investors can find this as an opportunity to buy Apple stock, because every time a company comes up with an innovative product, it leads to an increase in its stock price. So with that in mind, we can say that this is the best time to analyze Apple’s stock prices.

Dataset: -

For the Apple stock price prediction task, you need to download an Apple stock price dataset. To download a dataset for this task, follow the steps mentioned below:

  1. Visit Yahoo Finance
  2. Search for Apple or AAPL (it’s the stock symbol of Apple)
  3. Then click on Historical data
  4. And at last click on download

After these steps, you will see a CSV file in your download folder.

Step 1: Import all the required libraries

  • Pandas : In computer programming, pandas is a software library written for the Python programming language for data manipulation and analysis and storing in a proper way. In particular, it offers data structures and operations for manipulating numerical tables and time series
  • Sklearn : Scikit-learn (formerly scikits.learn) is a free software machine learning library for the Python programming language. It features various classification, regression and clustering algorithms including support vector machines, random forests, gradient boosting, k-means and DBSCAN, and is designed to interoperate with the Python numerical and scientific libraries NumPy and SciPy. The library is built upon the SciPy (Scientific Python) that must be installed before you can use scikit-learn.
  • Pickle : Python pickle module is used for serializing and de-serializing a Python object structure. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script.
  • Seaborn : Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
  • Matplotlib : Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK.
#Loading libraries 
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import sklearn.linear_model
import sklearn
import pickle
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import OneHotEncoder
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
from sklearn.metrics import mean_absolute_percentage_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from sklearn.preprocessing import scale
from sklearn.linear_model import LinearRegression, Ridge, RidgeCV, Lasso, LassoCV
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.decomposition import PCA
import warnings




warnings.filterwarnings('ignore')

Step 2 : Read dataset and basic details of dataset

Goal:- In this step we are going to read the dataset, view the dataset and analysis the basic details like total number of rows and columns, what are the column data types and see to need to create new column or not.

In this stage we are going to read our problem dataset and have a look on it.

#loading the dataset
try:
df = pd.read_csv('C:/Users/YAJENDRA/Documents/final notebooks/Apple Stock Price Prediction/data/AAPL (1).csv') #Path for the file
print('Data read done successfully...')
except (FileNotFoundError, IOError):
print("Wrong file or file path")
Data read done successfully...# To view the content inside the dataset we can use the head() method that returns a specified number of rows, string from the top.
# The head() method returns the first 5 rows if a number is not specified.
df.head()
png

Step3: Data Preprocessing

Why need of Data Preprocessing?

Preprocessing data is an important step for data analysis. The following are some benefits of preprocessing data:

  • It improves accuracy and reliability. Preprocessing data removes missing or inconsistent data values resulting from human or computer error, which can improve the accuracy and quality of a dataset, making it more reliable.
  • It makes data consistent. When collecting data, it’s possible to have data duplicates, and discarding them during preprocessing can ensure the data values for analysis are consistent, which helps produce accurate results.
  • It increases the data’s algorithm readability. Preprocessing enhances the data’s quality and makes it easier for machine learning algorithms to read, use, and interpret it.

After we read the data, we can look at the data using:

# count the total number of rows and columns.
print ('The train data has {0} rows and {1} columns'.format(df.shape[0],df.shape[1]))
The train data has 251 rows and 7 columns

The df.value_counts() method counts the number of types of values a particular column contains.

df.shape(251, 7)

The df.shape method shows the shape of the dataset.

df.info()<class 'pandas.core.frame.DataFrame'>
RangeIndex: 251 entries, 0 to 250
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 251 non-null object
1 Open 251 non-null float64
2 High 251 non-null float64
3 Low 251 non-null float64
4 Close 251 non-null float64
5 Adj Close 251 non-null float64
6 Volume 251 non-null int64
dtypes: float64(5), int64(1), object(1)
memory usage: 13.9+ KB

The df.info() method prints information about a DataFrame including the index dtype and columns, non-null values and memory usage.

df.iloc[1]Date         2022-02-08
Open 171.729996
High 175.350006
Low 171.429993
Close 174.830002
Adj Close 174.042633
Volume 74829200
Name: 1, dtype: object

df.iloc[ ] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array. The iloc property gets, or sets, the value(s) of the specified indexes.

Data Type Check for every column

Why data type check is required?

Data type check helps us with understanding what type of variables our dataset contains. It helps us with identifying whether to keep that variable or not. If the dataset contains contiguous data, then only float and integer type variables will be beneficial and if we have to classify any value then categorical variables will be beneficial.

objects_cols = ['object']
objects_lst = list(df.select_dtypes(include=objects_cols).columns)
print("Total number of categorical columns are ", len(objects_lst))
print("There names are as follows: ", objects_lst)
Total number of categorical columns are 1
There names are as follows: ['Date']
int64_cols = ['int64']
int64_lst = list(df.select_dtypes(include=int64_cols).columns)
print("Total number of numerical columns are ", len(int64_lst))
print("There names are as follows: ", int64_lst)
Total number of numerical columns are 1
There names are as follows: ['Volume']
float64_cols = ['float64']
float64_lst = list(df.select_dtypes(include=float64_cols).columns)
print("Total number of float64 columns are ", len(float64_lst))
print("There name are as follow: ", float64_lst)
Total number of float64 columns are 5
There name are as follow: ['Open', 'High', 'Low', 'Close', 'Adj Close']

Step 2 Insights: -

  1. We have total 7 features where 5 of them are float type, 1 are object type and 1 is int type.

After this step we have to calculate various evaluation parameters which will help us in cleaning and analysing the data more accurately.

Step 3: Descriptive Analysis

Goal/Purpose: Finding the data distribution of the features. Visualization helps to understand data and also to explain the data to another person.

Things we are going to do in this step:

  1. Mean
  2. Median
  3. Mode
  4. Standard Deviation
  5. Variance
  6. Null Values
  7. NaN Values
  8. Min value
  9. Max value
  10. Count Value
  11. Quatilers
  12. Correlation
  13. Skewness
df.describe()
png

The df.describe() method returns description of the data in the DataFrame. If the DataFrame contains numerical data, the description contains these information for each column: count — The number of not-empty values. mean — The average (mean) value.

Measure the variability of data of the dataset

Variability describes how far apart data points lie from each other and from the center of a distribution.

1. Standard Deviation

Standard-Deviation-ADD-SOURCE-e838b9dcfb89406e836ccad58278f4cd.jpg

The standard deviation is the average amount of variability in your dataset.

It tells you, on average, how far each data point lies from the mean. The larger the standard deviation, the more variable the data set is and if zero variance then there is no variability in the dataset that means there no use of that dataset.

So, it helps in understanding the measurements when the data is distributed. The more the data is distributed, the greater will be the standard deviation of that data.Here, you as an individual can determine which company is beneficial in long term. But, if you didn’t know the SD you would have choosen a wrong compnay for you.

df.std()Open         1.292059e+01
High 1.280172e+01
Low 1.292665e+01
Close 1.289737e+01
Adj Close 1.271308e+01
Volume 2.306233e+07
dtype: float64

We can also understand the standard deviation using the below function.

def std_cal(df,float64_lst):

cols = ['normal_value', 'zero_value']
zero_value = 0
normal_value = 0

for value in float64_lst:

rs = round(df[value].std(),6)

if rs > 0:
normal_value = normal_value + 1

elif rs == 0:
zero_value = zero_value + 1

std_total_df = pd.DataFrame([[normal_value, zero_value]], columns=cols)

return std_total_df
std_cal(df, float64_lst)
png
int64_cols = ['int64']
int64_lst = list(df.select_dtypes(include=int64_cols).columns)
std_cal(df,int64_lst)
png

zero_value -> is the zero variance and when then there is no variability in the dataset that means there no use of that dataset.

2. Variance

The variance is the average of squared deviations from the mean. A deviation from the mean is how far a score lies from the mean.

Variance is the square of the standard deviation. This means that the units of variance are much larger than those of a typical value of a data set.

0_5NGAJWo_3-DsLKoV.png
Variance-TAERM-ADD-Source-464952914f77460a8139dbf20e14f0c0.jpg

Why do we used Variance ?

By Squairng the number we get non-negative computation i.e. Disperson cannot be negative. The presence of variance is very important in your dataset because this will allow the model to learn about the different patterns hidden in the data

df.var()Open         1.669415e+02
High 1.638840e+02
Low 1.670982e+02
Close 1.663422e+02
Adj Close 1.616224e+02
Volume 5.318710e+14
dtype: float64

We can also understand the Variance using the below function.

zero_cols = []

def var_cal(df,float64_lst):

cols = ['normal_value', 'zero_value']
zero_value = 0
normal_value = 0

for value in float64_lst:

rs = round(df[value].var(),6)

if rs > 0:
normal_value = normal_value + 1

elif rs == 0:
zero_value = zero_value + 1
zero_cols.append(value)

var_total_df = pd.DataFrame([[normal_value, zero_value]], columns=cols)

return var_total_df
var_cal(df, float64_lst)
png
var_cal(df, int64_lst)
png

zero_value -> Zero variance means that there is no difference in the data values, which means that they are all the same.

Measure central tendency

A measure of central tendency is a single value that attempts to describe a set of data by identifying the central position within that set of data. As such, measures of central tendency are sometimes called measures of central location. They are also classed as summary statistics.

Mean — The average value. Median — The mid point value. Mode — The most common value.

1. Mean

1_tjAEMZx_0uIYGUhxEnPXPw.png

The mean is the arithmetic average, and it is probably the measure of central tendency that you are most familiar.

Why do we calculate mean?

The mean is used to summarize a data set. It is a measure of the center of a data set.

df.mean()Open         1.516037e+02
High 1.537352e+02
Low 1.495902e+02
Close 1.517478e+02
Adj Close 1.513879e+02
Volume 8.556671e+07
dtype: float64

We can also understand the mean using the below function.

def mean_cal(df,int64_lst):

cols = ['normal_value', 'zero_value']
zero_value = 0
normal_value = 0

for value in int64_lst:

rs = round(df[value].mean(),6)

if rs > 0:
normal_value = normal_value + 1

elif rs == 0:
zero_value = zero_value + 1

mean_total_df = pd.DataFrame([[normal_value, zero_value]], columns=cols)

return mean_total_df
mean_cal(df, int64_lst)
png
mean_cal(df,float64_lst)
png

zero_value -> that the mean of a paticular column is zero, which isn’t usefull in anyway and need to be drop.

2.Median

Alg1_14_02_0011-diagram_thumb-lg.png

The median is the middle value. It is the value that splits the dataset in half.The median of a dataset is the value that, assuming the dataset is ordered from smallest to largest, falls in the middle. If there are an even number of values in a dataset, the middle two values are the median.

Why do we calculate median ?

By comparing the median to the mean, you can get an idea of the distribution of a dataset. When the mean and the median are the same, the dataset is more or less evenly distributed from the lowest to highest values.The median will depict that the patient below median is Malignent and above that are Benign.

df.median()Open         1.495000e+02
High 1.515700e+02
Low 1.478200e+02
Close 1.504300e+02
Adj Close 1.501800e+02
Volume 8.038940e+07
dtype: float64

We can also understand the median using the below function.

def median_cal(df,int64_lst):

cols = ['normal_value', 'zero_value']
zero_value = 0
normal_value = 0

for value in int64_lst:

rs = round(df[value].mean(),6)

if rs > 0:
normal_value = normal_value + 1

elif rs == 0:
zero_value = zero_value + 1

median_total_df = pd.DataFrame([[normal_value, zero_value]], columns=cols)

return median_total_df
median_cal(df, float64_lst)
png
median_cal(df, int64_lst)
png

zero_value -> that the median of a paticular column is zero which isn’t usefull in anyway and need to be drop.

3. Mode

The mode is the value that occurs the most frequently in your data set. On a bar chart, the mode is the highest bar. If the data have multiple values that are tied for occurring the most frequently, you have a multimodal distribution. If no value repeats, the data do not have a mode.

Why do we calculate mode ?

The mode can be used to summarize categorical variables, while the mean and median can be calculated only for numeric variables. This is the main advantage of the mode as a measure of central tendency. It’s also useful for discrete variables and for continuous variables when they are expressed as intervals.

df.mode()
png
def mode_cal(df,int64_lst):

cols = ['normal_value', 'zero_value', 'string_value']
zero_value = 0
normal_value = 0
string_value = 0

for value in int64_lst:

rs = df[value].mode()[0]

if isinstance(rs, str):
string_value = string_value + 1
else:

if rs > 0:
normal_value = normal_value + 1

elif rs == 0:
zero_value = zero_value + 1

mode_total_df = pd.DataFrame([[normal_value, zero_value, string_value]], columns=cols)

return mode_total_df
mode_cal(df, list(df.columns))
png

zero_value -> that the mode of a paticular column is zero which isn’t usefull in anyway and need to be drop.

Null and Nan values

  1. Null Values
missing-values.png

A null value in a relational database is used when the value in a column is unknown or missing. A null is neither an empty string (for character or datetime data types) nor a zero value (for numeric data types).

df.isnull().sum()Date         0
Open 0
High 0
Low 0
Close 0
Adj Close 0
Volume 0
dtype: int64

As we notice that there are no null values in our dataset.

  1. Nan Values
images.png

NaN, standing for Not a Number, is a member of a numeric data type that can be interpreted as a value that is undefined or unrepresentable, especially in floating-point arithmetic.

df.isna().sum()Date         0
Open 0
High 0
Low 0
Close 0
Adj Close 0
Volume 0
dtype: int64

As we notice that there are no nan values in our dataset.

# We have many ways to fill Null/Nan Values as below:
  • mean -> average value (for numerical)
  • mode -> most repeated value (for categorical)

Another way to remove null and nan values is to use the method “df.dropna(inplace=True)”.

Count of unique occurences of every value in all categorical value

for value in objects_lst:

print(f"{value:{10}} {df[value].value_counts()}")
Date 2022-02-07 1
2022-10-13 1
2022-09-26 1
2022-09-27 1
2022-09-28 1
..
2022-06-14 1
2022-06-15 1
2022-06-16 1
2022-06-17 1
2023-02-06 1
Name: Date, Length: 251, dtype: int64

However, Date is a reference to a particular day represented within a calendar system.

And hence we wont be needing it.

df
png

Skewness

Skewness is a measure of the asymmetry of a distribution. A distribution is asymmetrical when its left and right side are not mirror images. A distribution can have right (or positive), left (or negative), or zero skewness

Why do we calculate Skewness ?

Skewness gives the direction of the outliers if it is right-skewed, most of the outliers are present on the right side of the distribution while if it is left-skewed, most of the outliers will present on the left side of the distribution

Below is the function to calculate skewness.

def right_nor_left(df, int64_lst):

temp_skewness = ['column', 'skewness_value', 'skewness (+ve or -ve)']
temp_skewness_values = []

temp_total = ["positive (+ve) skewed", "normal distrbution" , "negative (-ve) skewed"]
positive = 0
negative = 0
normal = 0

for value in int64_lst:

rs = round(df[value].skew(),4)

if rs > 0:
temp_skewness_values.append([value,rs , "positive (+ve) skewed"])
positive = positive + 1

elif rs == 0:
temp_skewness_values.append([value,rs,"normal distrbution"])
normal = normal + 1

elif rs < 0:
temp_skewness_values.append([value,rs, "negative (-ve) skewed"])
negative = negative + 1

skewness_df = pd.DataFrame(temp_skewness_values, columns=temp_skewness)
skewness_total_df = pd.DataFrame([[positive, normal, negative]], columns=temp_total)

return skewness_df, skewness_total_df
float64_cols = ['float64','int64']
float64_lst_col = list(df.select_dtypes(include=float64_cols).columns)

skew_df,skew_total_df = right_nor_left(df, float64_lst_col)
skew_df
png
skew_total_df
png

We notice with the above results that we have following details:

  1. 6 columns are positive skewed.

Step 3 Insights: -

With the statistical analysis we have found that the data have 6 columns with +ve skewness.

Statistical analysis is little difficult to understand at one glance so to make it more understandable we will perform visulatization on the data which will help us to understand the process easily.

Why we are calculating all these metrics?

Mean / Median /Mode/ Variance /Standard Deviation are all very basic but very important concept of statistics used in data science. Almost all the machine learning algorithm uses these concepts in data preprocessing steps. These concepts are part of descriptive statistics where we basically used to describe and understand the data for features in Machine learning

Step 4: Data Exploration

Goal/Purpose:

Graphs we are going to develop in this step

  1. Histogram of all columns to check the distrubution of the columns
  2. Distplot or distribution plot of all columns to check the variation in the data distribution
  3. Heatmap to calculate correlation within feature variables
  4. Boxplot to find out outlier in the feature columns

1. Histogram

A histogram is a bar graph-like representation of data that buckets a range of classes into columns along the horizontal x-axis.The vertical y-axis represents the number count or percentage of occurrences in the data for each column

# Distribution in attributes
%matplotlib inline
import matplotlib.pyplot as plt
df.hist(bins=50, figsize=(30,30))
plt.show()
png

Histogram Insight: -

Histogram helps in identifying the following:

  • View the shape of your data set’s distribution to look for outliers or other significant data points.
  • Determine whether something significant has boccurred from one time period to another.

Why Histogram?

It is used to illustrate the major features of the distribution of the data in a convenient form. It is also useful when dealing with large data sets (greater than 100 observations). It can help detect any unusual observations (outliers) or any gaps in the data.

From the above graphical representation we can identify that the highest bar represents the outliers which is above the maximum range.

We can also identify that the values are moving on the right side, which determines positive and the centered values determines normal skewness.

2. Distplot

A Distplot or distribution plot, depicts the variation in the data distribution. Seaborn Distplot represents the overall distribution of continuous data variables. The Seaborn module along with the Matplotlib module is used to depict the distplot with different variations in it

num = [f for f in df.columns if df.dtypes[f] != 'object']
nd = pd.melt(df, value_vars = num)
n1 = sns.FacetGrid (nd, col='variable', col_wrap=4, sharex=False, sharey = False)
n1 = n1.map(sns.distplot, 'value')
n1
<seaborn.axisgrid.FacetGrid at 0x20172f88d50>
png

Distplot Insights: -

Above is the distrution bar graphs to confirm about the statistics of the data about the skewness, the above results are:

  1. 6 columns are positive skewed

Why Distplot?

Skewness is demonstrated on a bell curve when data points are not distributed symmetrically to the left and right sides of the median on a bell curve. If the bell curve is shifted to the left or the right, it is said to be skewed.

We can observe that the bell curve is shifted to left we indicates positive skewness.As all the column are positively skewed we don’t need to do scaling.

Let’s proceed and check the distribution of the target variable.

The target variable is positively skewed.A normally distributed (or close to normal) target variable helps in better modeling the relationship between target and independent variables.

3. Heatmap

A heatmap (or heat map) is a graphical representation of data where values are depicted by color.Heatmaps make it easy to visualize complex data and understand it at a glance

Correlation — A positive correlation is a relationship between two variables in which both variables move in the same direction. Therefore, when one variable increases as the other variable increases, or one variable decreases while the other decreases.

Correlation can have a value:

  • 1 is a perfect positive correlation
  • 0 is no correlation (the values don’t seem linked at all)
  • -1 is a perfect negative correlation
#correlation plot
sns.set(rc = {'figure.figsize':(25,20)})
corr = df.corr().abs()
sns.heatmap(corr,annot=True)
plt.show()
png

Notice the last column from right side of this map. We can see the correlation of all variables against diagnosis. As you can see, some variables seem to be strongly correlated with the target variable. Here, a numeric correlation score will help us understand the graph better.

print (corr['Close'].sort_values(ascending=False)[:10], '\n') #top 15 values
print ('----------------------')
print (corr['Close'].sort_values(ascending=False)[-10:]) #last 5 values`
Close 1.000000
Adj Close 0.999874
Low 0.990997
High 0.990157
Open 0.975471
Volume 0.087517
Name: Close, dtype: float64

----------------------
Close 1.000000
Adj Close 0.999874
Low 0.990997
High 0.990157
Open 0.975471
Volume 0.087517
Name: Close, dtype: float64

Here we see that the concave points_worst feature is 79% correlated with the target variable. Concave points represent the number of indentations present on the nuclear border.This parameter was found to be statistically significant (P < 0.0001) in differentiating hyperplasia from carcinoma.

corr
png

Heatmap insights: -

As we know, it is recommended to avoid correlated features in your dataset. Indeed, a group of highly correlated features will not bring additional information (or just very few), but will increase the complexity of the algorithm, hence increasing the risk of errors.

Why Heatmap?

Heatmaps are used to show relationships between two variables, one plotted on each axis. By observing how cell colors change across each axis, you can observe if there are any patterns in value for one or both variables.

4. Boxplot

211626365402575-b88c4d0fdacd5abb4c3dc2de3bc004bb.png

A boxplot is a standardized way of displaying the distribution of data based on a five number summary (“minimum”, first quartile [Q1], median, third quartile [Q3] and “maximum”).

Basically, to find the outlier in a dataset/column.

features = [  'Open', 'High', 'Low'
, 'Adj Close', 'Volume'
]
sns.boxplot(data=df)<Axes: >
png

The dark points are known as Outliers. Outliers are those data points that are significantly different from the rest of the dataset. They are often abnormal observations that skew the data distribution, and arise due to inconsistent data entry, or erroneous observations.

Boxplot Insights: -

  • Sometimes outliers may be an error in the data and should be removed. In this case these points are correct readings yet they are different from the other points that they appear to be incorrect.
  • The best way to decide wether to remove them or not is to train models with and without these data points and compare their validation accuracy.
  • So we will keep it unchanged as it won’t affect our model.

Here, we can see that most of the variables possess outlier values. It would take us days if we start treating these outlier values one by one. Hence, for now we’ll leave them as is and let our algorithm deal with them. As we know, tree-based algorithms are usually robust to outliers.

Why Boxplot?

Box plots are used to show distributions of numeric data values, especially when you want to compare them between multiple groups. They are built to provide high-level information at a glance, offering general information about a group of data’s symmetry, skew, variance, and outliers.

Step 2: Data Preparation

Goal:-

Tasks we are going to in this step:

  1. Now we will spearate the target variable and feature columns in two different dataframe and will check the shape of the dataset for validation purpose.
  2. Split dataset into train and test dataset.
  3. Scaling on train dataset.

1. Now we spearate the target variable and feature columns in two different dataframe and will check the shape of the dataset for validation purpose.

# Separate target and feature column in X and y variable

target = 'Close'

# X will be the features
X = df[["High", "Open", "Low"]]
#y will be the target variable
y = df[target]
Xy# Check the shape of X and y variable
X.shape, y.shape
# Reshape the y variable
y = y.values.reshape(-1,1)
# Again check the shape of X and y variable
X.shape, y.shape

2. Spliting the dataset in training and testing data.

Here we are spliting our dataset into 80/20 percentage where 80% dataset goes into the training part and 20% goes into testing part.

# Split the X and y into X_train, X_test, y_train, y_test variables with 80-20% split.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Check shape of the splitted variables
X_train.shape, X_test.shape, y_train.shape, y_test.shape

Insights: -

Train test split technique is used to estimate the performance of machine learning algorithms which are used to make predictions on data not used to train the model.It is a fast and easy procedure to perform, the results of which allow you to compare the performance of machine learning algorithms for your predictive modeling problem. Although simple to use and interpret, there are times when the procedure should not be used, such as when you have a small dataset and situations where additional configuration is required, such as when it is used for classification and the dataset is not balanced.

In the next step we will train our model on the basis of our training and testing data.

Step 3: Model Training

Goal:

In this step we are going to train our dataset on DecisionTree Regressor algorithms. As we know that our target variable is in continuous format so we have to apply regression algorithm.

Algorithms we are going to use in this step

  1. DecisionTree Regressor
  2. Linear Regression (no regularization)
  3. Lasso Regression (L1 regularization)
  4. Ridge Regression (L2 regularization)

K-fold cross validation is a procedure used to estimate the skill of the model on new data. There are common tactics that you can use to select the value of k for your dataset. There are commonly used variations on cross-validation, such as stratified and repeated, that are available in scikit-learn

# Define kfold with 10 split
cv = KFold(n_splits=10, shuffle=True, random_state=42)

The goal of cross-validation is to test the model’s ability to predict new data that was not used in estimating it, in order to flag problems like overfitting or selection bias and to give an insight on how the model will generalize to an independent dataset (i.e., an unknown dataset, for instance from a real problem).

1. DecisionTree Regressor

Regression trees are used for dependent variable with continuous values and classification trees are used for dependent variable with discrete values. Basic Theory : Decision tree is derived from the independent variables, with each node having a condition over a feature.

Decision Tree is one of the most commonly used, practical approaches for supervised learning. It can be used to solve both Regression and Classification tasks with the latter being put more into practical application. It is a tree-structured classifier with three types of nodes.

What does it do?

Decision tree builds regression or classification models in the form of a tree structure. It breaks down a dataset into smaller and smaller subsets while at the same time an associated decision tree is incrementally developed. The final result is a tree with decision nodes and leaf nodes.

from sklearn.tree import DecisionTreeRegressor
DTR = DecisionTreeRegressor()
DTR.fit(X_train, y_train)
#Accuracy check of trainig data

#Get R2 score
DTR.score(X_train, y_train)
#Accuracy check of test data

#Get R2 score
DTR.score(X_test, y_test)
# Getting kfold values
DTR_scores = -1 * cross_val_score(DTR,
X_train,
y_train,
cv=cv,
scoring='neg_root_mean_squared_error')
DTR_scores
# Mean of the train kfold scores
DTR_score_train = np.mean(DTR_scores)
DTR_score_train

Prediction

Now we will perform prediction on the dataset using DecisionTree Regressor.

y_predicted = DTR.predict(X_test)

2. Linear Regression(no regularization)

Linear regression analysis is used to predict the value of a variable based on the value of another variable. The variable you want to predict is called the dependent variable. The variable you are using to predict the other variable’s value is called the independent variable. Its comes under Supervised Learning technique.

So, Linear regression predicts the output of a numerical dependent variable. Therefore the outcome must be a numerical or continuous value.

Train set cross-validation

#Using Linear Regression Algorithm to the Training Set
from sklearn.linear_model import LinearRegression

lin_R = LinearRegression() #Object Creation

lin_R.fit(X_train, y_train)
#Accuracy check of trainig data

#Get R2 score
lin_R.score(X_train, y_train)
#Accuracy check of test data

#Get R2 score
lin_R.score(X_test, y_test)
# Getting kfold values
lr_scores = -1 * cross_val_score(lin_R,
X_train,
y_train,
cv=cv,
scoring='neg_root_mean_squared_error')
lr_scores
# Mean of the train kfold scores
lr_score_train = np.mean(lr_scores)
lr_score_train

Prediction

Now we will perform prediction on the dataset using Linear Regression.

# Predict the values on X_test_scaled dataset 
lr_predicted = lin_R.predict(X_test)
# Evaluating

from sklearn.metrics import mean_absolute_error

print("The model used is Linear Regression")

lr_score_test = mean_absolute_error(y_test,y_predicted)
print(f"\nThe MAE is: {lr_score_test} " )

lr_score_test= mean_squared_error(y_test, y_predicted)
print(f"\nThe MSE is: {lr_score_test} ")

lr_score_test = np.sqrt(mean_squared_error(y_test, y_predicted))
print(f"\nThe RMSE is: {lr_score_test}")

3. Lasso Regression (L1 regularization)

Lasso regression is a type of linear regression that uses shrinkage. Shrinkage is where data values are shrunk towards a central point, like the mean. The lasso procedure encourages simple, sparse models (i.e. models with fewer parameters). This particular type of regression is well-suited for models showing high levels of muticollinearity or when you want to automate certain parts of model selection, like variable selection/parameter elimination.

L1 Regularization

Lasso regression performs L1 regularization, which adds a penalty equal to the absolute value of the magnitude of coefficients. This type of regularization can result in sparse models with few coefficients; Some coefficients can become zero and eliminated from the model. Larger penalties result in coefficient values closer to zero, which is the ideal for producing simpler models. On the other hand, L2 regularization (e.g. Ridge regression) doesn’t result in elimination of coefficients or sparse models. This makes the Lasso far easier to interpret than the Ridge.

#Using Lasso Regression Method to the Training dataset
ls_reg = LassoCV()
ls_reg = ls_reg.fit(X_train, y_train)
#Accuracy check of trainig data
#Get R2 score
ls_reg.score(X_train, y_train)
#Accuracy check of test data
#Get R2 score
ls_reg.score(X_test, y_test)
#Get kfold values
lasso_scores = -1 * cross_val_score(ls_reg,
X_train,
y_train,
cv=cv,
scoring='neg_root_mean_squared_error')
lasso_scores
# Mean of the train kfold scores
lasso_score_train = np.mean(lasso_scores)
lasso_score_train

Prediction

# Predict the values on X_test_scaled dataset 
y_predicted = ls_reg.predict(X_test)
# Evaluating



print("The model used is Linear Regression")

lasso_score_test = mean_absolute_error(y_test,y_predicted)
print(f"\nThe MAE is: {lasso_score_test}")

lasso_score_test = mean_squared_error(y_test, y_predicted)
print(f"\nThe MSE is: {lasso_score_test}")

lasso_score_test = np.sqrt(mean_squared_error(y_test, y_predicted))
print(f"\nThe RMSE is: {lasso_score_test}")

#Visualize the data predictions = ls_predicted valid = df[X. shape [0]:] valid [‘Predictions’] = predictions plt.figure(figsize= (16,8)) plt.title(‘Model’) plt.xlabel(‘Days’) plt.ylabel(‘Close Price USD ($)’) plt.plot(df[‘Close’]) plt.plot(valid[[‘Close’, ‘Predictions’]]) plt.legend([‘Orig’, ‘Val’, ‘Pred’])

Evaluation: -

train_metrics = np.array([round(DTR_score_train,3),
round(lr_score_train,3),
round(lasso_score_train,3),

])
train_metrics = pd.DataFrame(train_metrics, columns=['RMSE (Train Set)'])
train_metrics.index = ['DecisionTree Regressor',
'Linear Regression',
'Lasso Regression',
#'Ridge Regression'
]
train_metrics
test_metrics = np.array([round(DTR_score_train,3),
round(lr_score_test,3),
round(lasso_score_test,3),

])
test_metrics = pd.DataFrame(test_metrics, columns=['RMSE (Test Set)'])
test_metrics.index = ['DecisionTree Regressor',
'Linear Regression',
'Lasso Regression',
#'Ridge Regression'
]
test_metrics

Insight:-

  • A low RMSE value indicates that the simulated and observed data are close to each other showing a better accuracy. Thus lower the RMSE better is model performance.
  • As You can see from above RMSE , we will go with DecisionTree Regressor.(According to our dataset).
  • But there is no universally “good” RMSE value. It all depends on the range of values in the dataset you’re working with.

Step 4: Save Model

Goal:- In this step we are going to save our model in pickel format file.

import pickle
pickle.dump(DTR , open('Apple_Stock_DTR.pkl', 'wb'))
import pickle
pickle.dump(lin_R , open('Apple_Stock_linear.pkl', 'wb'))
import pickle
pickle.dump(ls_reg , open('Apple_Stock_lasso.pkl', 'wb'))
import pickle

def model_prediction(features):

pickled_model = pickle.load(open('Apple_Stock_DTR.pkl', 'rb'))
Stock_Price = str(list(pickled_model.predict(features)))




return str(f'The Stock price is {Stock_Price}')
#"Open", "High", "Low"


Open = 172.860001
High = 173.949997
Low = 170.949997
model_prediction([[Open,High,Low]])df.iloc[0]

We can test our model by giving our own parameters or features to predict.

Conclusion

After observing the problem statement we have build an efficient model to overcome it. The above model helps in predicting the Price of Apple company Stocks. It will help the Investors to understand & when to invest money into Apple Stocks so they can get good returns in future.The accuracy for the prediction is 96.91%.

Checkout whole project code here (github repo).

🚀 Unlock Your Dream Job with HiDevs Community!

🔍 Seeking the perfect job? HiDevs Community is your gateway to career success in the tech industry. Explore free expert courses, job-seeking support, and career transformation tips.

💼 We offer an upskill program in Gen AI, Data Science, Machine Learning, and assist startups in adopting Gen AI at minimal development costs.

🆓 Best of all, everything we offer is completely free! We are dedicated to helping society.

Book free of cost 1:1 mentorship on any topic of your choice — topmate

✨ We dedicate over 30 minutes to each applicant’s resume, LinkedIn profile, mock interview, and upskill program. If you’d like our guidance, check out our services here

💡 Join us now, and turbocharge your career!

Deepak Chawla LinkedIn
Vijendra Singh LinkedIn
Yajendra Prajapati LinkedIn
YouTube Channel
Instagram Page
HiDevs LinkedIn
Project Youtube Link

--

--