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 for Finance
Machine Learning for Finance

Machine Learning for Finance: Principles and practice for financial insiders

Arrow left icon
Profile Icon James Le Profile Icon Jannes Klaas
Arrow right icon
$20.98 $29.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (59 Ratings)
eBook May 2019 456 pages 1st Edition
eBook
$20.98 $29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon James Le Profile Icon Jannes Klaas
Arrow right icon
$20.98 $29.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (59 Ratings)
eBook May 2019 456 pages 1st Edition
eBook
$20.98 $29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$20.98 $29.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

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 feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Machine Learning for Finance

Chapter 2. Applying Machine Learning to Structured Data

Structured data is a term used for any data that resides in a fixed field within a record or file, two such examples being relational databases and spreadsheets. Usually, structured data is presented in a table in which each column presents a type of value, and each row represents a new entry. Its structured format means that this type of data lends itself to classical statistical analysis, which is also why most data science and analysis work is done on structured data.

In day-to-day life, structured data is also the most common type of data available to businesses, and most machine learning problems that need to be solved in finance deal with structured data in one way or another. The fundamentals of any modern company's day-to-day running is built around structured data, including, transactions, order books, option prices, and suppliers, which are all examples of information usually collected in spreadsheets or databases.

This chapter...

The data


The dataset we will work with is a synthetic dataset of transactions generated by a payment simulator. The goal of this case study and the focus of this chapter is to find fraudulent transactions within a dataset, a classic machine learning problem many financial institutions deal with.

Note

Note: Before we go further, a digital copy of the code, as well as an interactive notebook for this chapter are accessible online, via the following two links:

An interactive notebook containing the code for this chapter can be found under https://www.kaggle.com/jannesklaas/structured-data-code

The code can also be found on GitHub, in this book's repository: https://github.com/PacktPublishing/Machine-Learning-for-Finance

The dataset we're using stems from the paper PaySim: A financial mobile money simulator for fraud detection, by E. A. Lopez-Rojas, A. Elmir, and S. Axelsson. The dataset can be found on Kaggle under this URL: https://www.kaggle.com/ntnu-testimon/paysim1.

Before we break it down...

Heuristic, feature-based, and E2E models


Before we dive into developing models to detect fraud, let's take a second to pause and ponder over the different kinds of models we could build.

  • A heuristic-based model is a simple "rule of thumb" developed purely by humans. Usually, the heuristic model stems from having an expert knowledge of the problem.

  • A feature-based model relies heavily on humans modifying the data to create new and meaningful features, which are then fed into a (simple) machine learning algorithm. This approach mixes expert knowledge with learning from data.

  • An E2E model learns purely from raw data. No human expertise is used, and the model learns everything directly from observations.

In our case, a heuristic-based model could be created to mark all transactions with the TRANSFER transaction type and an amount over $200,000 as fraudulent. Heuristic-based models have the advantage that they are both fast to develop and easy to implement; however, this comes with a pay-off, their...

The machine learning software stack


In this chapter, we will be using a range of different libraries that are commonly used in machine learning. Let's take a minute to look at our stack, which consists of the following software:

  • Keras: A neural network library that can act as a simplified interface to TensorFlow.

  • NumPy: Adds support for large, multidimensional arrays as well as an extensive collection of mathematical functions.

  • Pandas: A library for data manipulation and analysis. It's similar to Microsoft's Excel but in Python, as it offers data structures to handle tables and the tools to manipulate them.

  • Scikit-learn: A machine learning library offering a wide range of algorithms and utilities.

  • TensorFlow: A dataflow programming library that facilitates working with neural networks.

  • Matplotlib: A plotting library.

  • Jupyter: A development environment. All of the code examples in this book are available in Jupyter Notebooks.

The majority of this book is dedicated to working with the Keras...

The heuristic approach


Earlier in this chapter, we introduced the three models that we will be using to detect fraud, now it's time to explore each of them in more detail. We're going to start with the heuristic approach.

Let's start by defining a simple heuristic model and measuring how well it does at measuring fraud rates.

Making predictions using the heuristic model

We will be making our predictions using the heuristic approach over the entire training data set in order to get an idea of how well this heuristic model does at predicting fraudulent transactions.

The following code will create a new column, Fraud_Heuristic, and in turn assigns a value of 1 in rows where the type is TRANSFER, and the amount is more than $200,000:

df['Fraud_Heuristic '] = np.where(((df['type'] == 'TRANSFER') &(df['amount'] > 200000)),1,0)

With just two lines of code, it's easy to see how such a simple metric can be easy to write, and quick to deploy.

The F1 score

One important thing we must consider is the...

The feature engineering approach


The objective of feature engineering is to exploit the qualitative insight of humans in order to create better machine learning models. A human engineer usually uses three types of insight: intuition, expert domain knowledge, and statistical analysis. Quite often, it's possible to come up with features for a problem just from intuition.

As an example, in our fraud case, it seems intuitive that fraudsters will create new accounts for their fraudulent schemes and won't be using the same bank account that they pay for their groceries with.

Domain experts are able to use their extensive knowledge of a problem in order to come up with other such examples of intuition. They'll know more about how fraudsters behave and can craft features that indicate such behavior. All of these intuitions are then usually confirmed by statistical analysis, something that can even be used to open the possibilities of discovering new features.

Statistical analysis can sometimes turn...

Preparing the data for the Keras library


In Chapter 1, Neural Networks and Gradient-Based Optimization, we saw that neural networks would only take numbers as inputs. The issue for us in our dataset is that not all of the information in our table is numbers, some of it is presented as characters.

Therefore, in this section, we're going to work on preparing the data for Keras so that we can meaningfully work with it.

Before we start, let's look at the three types of data, Nominal, Ordinal, and Numerical:

  • Nominal data: This comes in discrete categories that cannot be ordered. In our case, the type of transfer is a nominal variable. There are four discrete types, but it does not make sense to put them in any order. For instance, TRANSFER cannot be more than CASH_OUT, so instead, they are just separate categories.

  • Ordinal data: This also comes in discrete categories, but unlike nominal data, it can be ordered. For example, if coffee comes in large, medium, and small sizes, those are distinct...

Creating predictive models with Keras


Our data now contains the following columns:

amount, 
oldBalanceOrig, 
newBalanceOrig, 
oldBalanceDest, 
newBalanceDest, 
isFraud, 
isFlaggedFraud, 
type_CASH_OUT, 
type_TRANSFER, isNight

Now that we've got the columns, our data is prepared, and we can use it to create a model.

Extracting the target

To train the model, a neural network needs a target. In our case, isFraud is the target, so we have to separate it from the rest of the data. We can do this by running:

y_df = df['isFraud']
x_df = df.drop('isFraud',axis=1)

The first step only returns the isFraud column and assigns it to y_df.

The second step returns all columns except isFraud and assigns them to x_df.

We also need to convert our data from a pandas DataFrame to NumPy arrays. The pandas DataFrame is built on top of NumPy arrays but comes with lots of extra bells and whistles that make all the preprocessing we did earlier possible. To train a neural network, however, we just need the underlying data...

A brief primer on tree-based methods


No chapter on structured data would be complete without mentioning tree-based methods, such as random forests or XGBoost.

It is worth knowing about them because, in the realm of predictive modeling for structured data, tree-based methods are very successful. However, they do not perform as well on more advanced tasks, such as image recognition or sequence-to-sequence modeling. This is the reason why the rest of the book does not deal with tree-based methods.

Note

Note: For a deeper dive into XGBoost, check out the tutorials on the XGBoost documentation page: http://xgboost.readthedocs.io. There is a nice explanation of how tree-based methods and gradient boosting work in theory and practice under the Tutorials section of the website.

A simple decision tree

The basic idea behind tree-based methods is the decision tree. A decision tree splits up data to create the maximum difference in outcomes.

Let's assume for a second that our isNight feature is the greatest...

E2E modeling


Our current approach relies on engineered features. As we discussed at the start of this chapter, an alternative method is E2E modeling. In E2E modeling, both raw and unstructured data about a transaction is used. This could include the description text of a transfer, video feeds from cameras monitoring a cash machine, or other sources of data. E2E is often more successful than feature engineering, provided that you have enough data available.

To get valid results, and to successfully train the data with an E2E model it can take millions of examples. Yet, often this is the only way to gain an acceptable result, especially when it is hard to codify the rules for something. Humans can recognize things in images well, but it is hard to come up with exact rules that distinguish things, which is where E2E shines.

In the dataset used for this chapter, we do not have access to more data, but the rest of the chapters of this book demonstrate various E2E models.

Exercises


If you visit https://kaggle.com, search for a competition that has structured data. One example is the Titanic competition. Here you can create a new kernel, do some feature engineering, and try to build a predictive model.

How much can you improve it by investing time in feature engineering versus model tweaking? Is there an E2E approach to the problem?

Summary


In this chapter, we have taken a structured data problem from raw data to strong and reliable predictive models. We have learned about heuristic, feature engineering, and E2E modeling. We have also seen the value of clear evaluation metrics and baselines.

In the next chapter, we will look into a field where deep learning truly shines, computer vision. Here, we will discover the computer vision pipeline, from working with simple models to very deep networks augmented with powerful preprocessing software. The ability to "see" empowers computers to enter completely new domains.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore advances in machine learning and how to put them to work in financial industries
  • Gain expert insights into how machine learning works, with an emphasis on financial applications
  • Discover advanced machine learning approaches, including neural networks, GANs, and reinforcement learning

Description

Machine Learning for Finance explores new advances in machine learning and shows how they can be applied across the financial sector, including insurance, transactions, and lending. This book explains the concepts and algorithms behind the main machine learning techniques and provides example Python code for implementing the models yourself. The book is based on Jannes Klaas’ experience of running machine learning training courses for financial professionals. Rather than providing ready-made financial algorithms, the book focuses on advanced machine learning concepts and ideas that can be applied in a wide variety of ways. The book systematically explains how machine learning works on structured data, text, images, and time series. You'll cover generative adversarial learning, reinforcement learning, debugging, and launching machine learning products. Later chapters will discuss how to fight bias in machine learning. The book ends with an exploration of Bayesian inference and probabilistic programming.

Who is this book for?

This book is ideal for readers who understand math and Python, and want to adopt machine learning in financial applications. The book assumes college-level knowledge of math and statistics.

What you will learn

  • Apply machine learning to structured data, natural language, photographs, and written text
  • Understand how machine learning can help you detect fraud, forecast financial trends, analyze customer sentiments, and more
  • Implement heuristic baselines, time series, generative models, and reinforcement learning in Python, scikit-learn, Keras, and TensorFlow
  • Delve into neural networks, and examine the uses of GANs and reinforcement learning
  • Debug machine learning applications and prepare them for launch
  • Address bias and privacy concerns in machine learning

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 30, 2019
Length: 456 pages
Edition : 1st
Language : English
ISBN-13 : 9781789134698
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 feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : May 30, 2019
Length: 456 pages
Edition : 1st
Language : English
ISBN-13 : 9781789134698
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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 153.97
Hands-On Machine Learning for Algorithmic Trading
$65.99
Mastering Python for Finance
$43.99
Machine Learning for Finance
$43.99
Total $ 153.97 Stars icon

Table of Contents

10 Chapters
Neural Networks and Gradient-Based Optimization Chevron down icon Chevron up icon
Applying Machine Learning to Structured Data Chevron down icon Chevron up icon
Utilizing Computer Vision Chevron down icon Chevron up icon
Understanding Time Series Chevron down icon Chevron up icon
Parsing Textual Data with Natural Language Processing Chevron down icon Chevron up icon
Using Generative Models Chevron down icon Chevron up icon
Reinforcement Learning for Financial Markets Chevron down icon Chevron up icon
Privacy, Debugging, and Launching Your Products Chevron down icon Chevron up icon
Fighting Bias Chevron down icon Chevron up icon
Bayesian Inference and Probabilistic Programming Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(59 Ratings)
5 star 59.3%
4 star 15.3%
3 star 8.5%
2 star 5.1%
1 star 11.9%
Filter icon Filter
Top Reviews

Filter reviews by




Tye M. Brown Dec 14, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Udemy Verified review Udemy
Jesus Encinas Castillo Sep 24, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Udemy Verified review Udemy
Hassan Alam Apr 20, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Udemy Verified review Udemy
Mark Heffernan May 29, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Udemy Verified review Udemy
Kenneth E. Mayer Jul 18, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
While going over supervised learning and unsupervised learning, the book also covers NLP with textual data and time series methods. The book is long but that is because it has many diagrams and much code.
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.