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

Arrow left icon
Profile Icon Jalaj Thanaki
Arrow right icon
zł59.99 zł141.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6 (5 Ratings)
eBook Apr 2018 566 pages 1st Edition
eBook
zł59.99 zł141.99
Paperback
zł177.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jalaj Thanaki
Arrow right icon
zł59.99 zł141.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6 (5 Ratings)
eBook Apr 2018 566 pages 1st Edition
eBook
zł59.99 zł141.99
Paperback
zł177.99
Subscription
Free Trial
eBook
zł59.99 zł141.99
Paperback
zł177.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
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 : 9781788398893
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 zł20 each
Feature tick icon Exclusive print discounts
$279.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 zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 597.97
Mastering Machine Learning Algorithms
zł197.99
Machine Learning Algorithms
zł221.99
Machine Learning Solutions
zł177.99
Total 597.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.