Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Machine Learning Solutions
Machine Learning Solutions

Machine Learning Solutions: Expert techniques to tackle complex machine learning problems using Python

eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Machine Learning Solutions

Chapter 2. Stock Market Price Prediction

In this chapter, we will cover an amazing application that belongs to predictive analysis. I hope the name of the chapter has already given you a rough idea of what this chapter is going to be all about. We will try to predict the price of the stock index. We will apply some modern machine learning techniques as well as deep learning techniques.

We will cover the following topics in this chapter:

  • Introducing the problem statement

  • Collecting the dataset

  • Understanding the dataset

  • Data preprocessing and data analysis

  • Feature engineering

  • Selecting the Machine Learning (ML) algorithm

  • Training the baseline model

  • Understanding the testing matrix

  • Testing the baseline model

  • Exploring problems with the existing approach

  • Understanding the revised approach

    • Understanding concepts and approaches

  • Implementing the revised approach

    • Testing the revised approach

    • Understanding problems with the revised approach

  • The best approach

  • Summary

So, let's get started!

Introducing the problem statement


The stock market is a place where you can buy and sell units of ownership in the company, which we call stocks. If the company performs well and increases its profit, then you will earn some profit as well because you have the stocks of the company, but if the company's profit goes down, then you will lose the money you have with the company. So if you invest your money in the right company at the right time, it could lead to you earning quite a lot of money. The question is which company's stock should you buy? Is there any way we can predict the future prices of the stock of any company given the historical prices of the company's stock so that we can have higher chances of getting good returns? The answer is yes. This is what we will explore in this chapter.

If you invest in the stock market, then you may have heard that stock prices are completely random and unpredictable. This is called the efficient market hypothesis, but a majority of the big financial...

Collecting the dataset


In order to build the model, first we need to collect the data. We will use the following two data points:

  • Dow Jones Industrial Average (DJIA) index prices

  • News articles

DJIA index prices give us an overall idea about the stock market's movements on a particular day, whereas news articles help us find out how news affects the stock prices. We will build our model using these two data points. Now let's collect the data.

Collecting DJIA index prices

In order to collect the DJIA index prices, we will use Yahoo Finance. You can visit this link: https://finance.yahoo.com/quote/%5EDJI/history?period1=1196706600&period2=1512325800&interval=1d&filter=history&frequency=1d. Once you click on this link, you can see that the price data shows up. You can change the time period and click on the Download Data link and that's it; you can have all the data in .csv file format. Refer to the following screenshot of the Yahoo finance DJIA index price page:

Figure 2.1: Yahoo...

Understanding the dataset


In this section, we will understand the meaning of data attributes, which will help us understand what kind of dataset we are going to deal with and what kind of preprocessing is needed for the dataset. We understand our dataset in two sections, and those sections are given as follows:

  • Understanding the DJIA dataset

  • Understanding the NYTimes news article dataset

Understanding the DJIA dataset

In the DJIA dataset, we have seven data attributes. They are quite easy to understand, so let's look at each of them one by one:

  • Date: The first column indicates the date in the YYYY-MM-DD format when you see data in the .csv file.

  • Open: This indicates the price at which the market opens, so it is the opening value for the DJIA index for that particular trading day.

  • High: This is the highest price for the DJIA index for a particular trading day.

  • Low: This is the lowest price for DJIA index for a particular trading day.

  • Close: The price of DJIA index at the close of the trading...

Data preprocessing and data analysis


In this section, we will mainly cover data preprocessing and data analysis. As a part of data preprocessing, we are preparing our training dataset. You may be wondering what kind of data preparation I'm talking about, considering we already have the data. Allow me to tell you that we have two different datasets and both datasets are independent. So, we need to merge the DJIA dataset and NYTimes news article dataset in order to get meaningful insights from these datasets. Once we prepare our training dataset, we can train the data using different machine learning (ML) algorithms.

Now let's start the coding to prepare the training dataset. We will be using numpy, csv, JSON, and pandas as our dependency libraries. Here, our code is divided into two parts. First, we will prepare the dataset for the DJIA index dataset and then we will move to the next part, which is preparing the NYTimes news article dataset. During the preparation of the training dataset,...

Feature engineering


As discussed earlier, we want to predict the close price for the DJIA index for a particular trading day. In this section, we will do feature selection based on our intuition for our basic prediction model for stock prices. We have already generated the training dataset. So, now we will load the saved .pkl format dataset and perform feature selection as well as minor data processing. We will also generate the sentiment score for each of the filtered NYTimes news articles and will use this sentiment score to train our baseline model. We will use the following Python dependencies:

  • numpy

  • pandas

  • nltk

This section has the following steps:

  1. Loading the dataset

  2. Minor preprocessing

  3. Feature selection

  4. Sentiment analysis

So, let's begin coding!

Loading the dataset

We have saved the data in the pickle format, and now we need to load data from it. You can refer to the following code snippet:

Figure 2.16: Code snippet for loading the dataset from the pickle file

You can refer to the code by clicking...

Selecting the Machine Learning algorithm


In this section, we will choose the Machine Learning (ML) algorithm based on our intuition and then perform training using our training dataset. This is the first model for this particular chapter, so the trained model is our baseline model, which we will improve later on. So, let's decide which kind of ML algorithm suits this stock price prediction application.

The stock price prediction application is a time-series analysis problem, where we need to predict the next point in the time series. This prediction activity is similar to linear regression, so we can say that this application is a kind of regression problem and any algorithm from the regression family should work. Let's select the ensemble algorithm, which is RandomForestRegressor, in order to develop our baseline model. So let's train our baseline model, and, based on the result of that model, we will modify our approach.

Training the baseline model


As you know, we have selected the RandomForestRegressor algorithm. We will be using the scikit-learn library to train the model. These are the steps we need to follow:

  1. Splitting the training and testing dataset

  2. Splitting prediction labels for the training and testing dataset

  3. Converting sentiment scores into the numpy array

  4. Training the ML model

So, let's implement each of these steps one by one.

Splitting the training and testing dataset

We have 10 years of data values. So for training purposes, we will be using 8 years of the data, which means the dataset from 2007 to 2014. For testing purposes, we will be using 2 years of the data, which means data from 2015 and 2016. You can refer to the code snippet in the following screenshot to implement this:

Figure 2.22: Splitting the training and testing dataset

As you can see from the preceding screenshot, our training dataset has been stored in the train dataframe and our testing dataset has been stored in the test dataframe...

Understanding the testing matrix


In this section, we will understand the testing matrix and visualization approaches to evaluate the performance of the trained ML model. So let's understand both approaches, which are as follows:

  • The default testing matrix

  • The visualization approach

The default testing matrix

We are using the default score API of scikit-learn to check how well the ML is performing. In this application, the score function is the coefficient of the sum of the squared error. It is also called the coefficient of R2, which is defined by the following equation:

Here, u indicates the residual sum of squares. The equation for u is as follows:

The variable v indicates the total sum of squares. The equation for v is as follows:

The best possible score is 1.0, and it can be a negative score as well. A negative score indicates that the trained model can be arbitrarily worse. A constant model that always predicts the expected value for label y, disregarding the input features, will produce an...

Testing the baseline model


In this section, we will be implementing our testing approach so that we can evaluate our model's accuracy. We will first generate the output prediction and then we'll start testing it. We will be implementing the following steps here:

  1. Generating and interpreting the output

  2. Generating the score

  3. Visualizing the output

Generating and interpreting the output

To generate the prediction, we are using the treeinterpreter library. We are predicting the price value for each of our testing dataset records using the following code:

Figure 2.26: Code snippet for generating the prediction

Here, prediction is the array in which we have elements that are the corresponding predicted adj close price for all records of the testing dataset. Now, we will compare this predicted output with the actual adj close price of the testing dataset. By doing this, we will get to know how accurately our first model is predicting the adj close price. In order to evaluate further, we will generate...

Exploring problems with the existing approach


In this section, we will be discussing the problems of the existing approach. There are mainly three errors we could have possibly committed, which are listed as follows:

  • Alignment

  • Smoothing

  • Trying a different ML algorithm

Let's discuss each of the points one by one.

Alignment

As we have seen in the graph, our actual price and predicted prices are not aligned with each other. This becomes a problem. We need to perform alignment on the price of the stocks. We need to consider the average value of our dataset, and based on that, we will generate the alignment. You can understand more about alignment in upcoming section called Alignment-based approach.

Smoothing

The second problem I feel we have with our first model is that we haven't applied any smoothing techniques. So for our model, we need to apply smoothing techniques as well. We will be using the Exponentially Weighted Moving Average (EWMA) technique for smoothing. This technique is used to adjust...

Understanding the revised approach


In this section, we will be looking at the key concepts and approaches for alignment and smoothing. It is not that difficult to implement the Logistic Regression algorithm; we will be using the scikit-learn API. So, we will start with understanding the concepts and approaches for implementation.

Understanding concepts and approaches

Here, we will discuss how alignment and smoothing will work. Once we understand the technicality behind alignment and smoothing, we will focus on the Logistic Regression-based approach.

Alignment-based approach

Using this approach, we will be increasing the prices using a constant value so that our predicted price and actual price in testing the dataset will be aligned. Suppose we take 10 days into consideration. We will generate the average of the value of the prices. After that, we generate the average value for the prices that have been predicted by the first ML model. Once we generate both average values, we need to subtract...

Implementing the revised approach


In this section, we will discuss the three parts of implementation, which are as follows:

  • Implementation

  • Testing the revised approach

  • Understanding the problem with the revised approach

Implementation

Here, we are implementing the following:

  • Alignment

  • Smoothing

  • Logistic Regression

We have already discussed the approach and key concepts, so now we just focus on the code part here. You can find all the code at this GitHub link: https://github.com/jalajthanaki/stock_price_prediction/blob/master/Stock_Price_Prediction.ipynb.

Implementing alignment

The alignment is performed on the testing dataset. You can refer to the following code snippet:

Figure 2.30: Code snippet for alignment on the test dataset

As you can see in the preceding code snippet, we obtain a difference of 10 days adj close price using the average price of the last 5 days and the average price of the predicted upcoming 5 days in order to align the test data. Here, we also convert the date from the string into...

The best approach


Here, we are going to implement the neural network-based algorithm multilayer perceptron (MLP). You can refer to the following code snippet:

Figure 2.37: Code snippet for multilayer perceptron

Here, you can see that we are using the Relu activation function, and the gradient descent solver function is ADAM. We are using a learning rate of 0.0001. You can evaluate the result by referring to the following graph:

Figure 2.38: Code snippet for generating the graph for the actual and predicted prices

This graph shows that all the data records' predicted prices follow the actual price pattern. You can say that our MLP model works well to predict the stock market prices. You can find the code at this GitHub link: https://github.com/jalajthanaki/stock_price_prediction/blob/master/Stock_Price_Prediction.ipynb.

Summary


In this chapter, you learned how to predict stock prices. We covered the different machine learning algorithms that can help us in this. We tried Random Forest Regressor, Logistic Regression, and multilayer perceptron. We found out that the multilayer perceptron works really well. I really want to discuss something beyond what we have done so far. If you are under the impression that using the sentiment analysis of news and predictive methods, we can now correctly predict the stock market price with a hundred percent accuracy, then you would be wrong. We can't predict stock prices with a hundred percent accuracy. Many communities, financial organizations, and academic researchers are working in this direction in order to make a stock market price predictive model that is highly accurate. This is an active research area.

So if you are interested in research and freelancing, then you can join some pretty cool communities. There are two communities that are quite popular. One of these...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Master the advanced concepts, methodologies, and use cases of machine learning
  • • Build ML applications for analytics, NLP and computer vision domains
  • • Solve the most common problems in building machine learning models

Description

Machine learning (ML) helps you find hidden insights from your data without the need for explicit programming. This book is your key to solving any kind of ML problem you might come across in your job. You’ll encounter a set of simple to complex problems while building ML models, and you'll not only resolve these problems, but you’ll also learn how to build projects based on each problem, with a practical approach and easy-to-follow examples. The book includes a wide range of applications: from analytics and NLP, to computer vision domains. Some of the applications you will be working on include stock price prediction, a recommendation engine, building a chat-bot, a facial expression recognition system, and many more. The problem examples we cover include identifying the right algorithm for your dataset and use cases, creating and labeling datasets, getting enough clean data to carry out processing, identifying outliers, overftting datasets, hyperparameter tuning, and more. Here, you'll also learn to make more timely and accurate predictions. In addition, you'll deal with more advanced use cases, such as building a gaming bot, building an extractive summarization tool for medical documents, and you'll also tackle the problems faced while building an ML model. By the end of this book, you'll be able to fine-tune your models as per your needs to deliver maximum productivity.

Who is this book for?

This book is for the intermediate users such as machine learning engineers, data engineers, data scientists, and more, who want to solve simple to complex machine learning problems in their day-to-day work and build powerful and efficient machine learning models. A basic understanding of the machine learning concepts and some experience with Python programming is all you need to get started with this book.

What you will learn

  • • Select the right algorithm to derive the best solution in ML domains
  • • Perform predictive analysis effciently using ML algorithms
  • • Predict stock prices using the stock index value
  • • Perform customer analytics for an e-commerce platform
  • • Build recommendation engines for various domains
  • • Build NLP applications for the health domain
  • • Build language generation applications using different NLP techniques
  • • Build computer vision applications such as facial emotion recognition

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 27, 2018
Length: 566 pages
Edition : 1st
Language : English
ISBN-13 : 9781788390040
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 27, 2018
Length: 566 pages
Edition : 1st
Language : English
ISBN-13 : 9781788390040
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 111.97
Mastering Machine Learning Algorithms
€36.99
Machine Learning Algorithms
€41.99
Machine Learning Solutions
€32.99
Total 111.97 Stars icon

Table of Contents

11 Chapters
Credit Risk Modeling Chevron down icon Chevron up icon
Stock Market Price Prediction Chevron down icon Chevron up icon
Customer Analytics Chevron down icon Chevron up icon
Recommendation Systems for E-Commerce Chevron down icon Chevron up icon
Sentiment Analysis Chevron down icon Chevron up icon
Job Recommendation Engine Chevron down icon Chevron up icon
Text Summarization Chevron down icon Chevron up icon
Developing Chatbots Chevron down icon Chevron up icon
Building a Real-Time Object Recognition App Chevron down icon Chevron up icon
Face Recognition and Face Emotion Recognition Chevron down icon Chevron up icon
Building Gaming Bot Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(5 Ratings)
5 star 60%
4 star 40%
3 star 0%
2 star 0%
1 star 0%
EDDY GIMENEZ Dec 08, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
there is no waste in it, everything is clear and very well documented for the purpose of learning the different approaches to apply in machine learning algorithms.
Amazon Verified review Amazon
Amazon buyer Jul 12, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book.
Amazon Verified review Amazon
Anish Shah Sep 20, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A practical approach towards Machine learning...The use of real-world datasets for various applications is very thoughtful by the author as it greatly reduces the learning curve. Highly recommended for those who want to practice real projects using scikit-learn library of Python...
Amazon Verified review Amazon
Dr. Franco Arda Sep 10, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I did not like Jalay's first book on NLP, but this one is pretty good.This book covers 11 topics in ML.It's impossible to be an expert at all 11 topics ranging from structured data to NLP and RL.Again, NLP is not her forte - see chapter 5 on Sentiment Analysis.I particular loved Chapter 3: CUSTOMER ANALYTICS. The author is very strong at structured data analysis, creating hypothesis, visualizing ....check our her corresponding Notebook on GitHub. Anyone who thinks he's good at ML because of a high score on a Kaggle competition will face the brutal reality of a Data Scientist with chapter 3.Jalay labels churn customers manually. That's really hard as there's no clear cut to when a customer turns profitable or not.It's data wrangling at it's best. Really impressive.Kudos
Amazon Verified review Amazon
Amazon Customer Aug 30, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
It's good in understanding the ML in hands on wise. However it would be helpful if parallel codes available in github are updated according to Tensorflow latest version.when I trying the samples available for seq2seq in github doesnt work for Tensorflow latest version.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.