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
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (59 Ratings)
Paperback May 2019 456 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon James Le Profile Icon Jannes Klaas
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (59 Ratings)
Paperback May 2019 456 pages 1st Edition
eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
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 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 : 9781789136364
Category :
Languages :

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 : May 30, 2019
Length: 456 pages
Edition : 1st
Language : English
ISBN-13 : 9781789136364
Category :
Languages :

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 115.97
Hands-On Machine Learning for Algorithmic Trading
€49.99
Mastering Python for Finance
€32.99
Machine Learning for Finance
€32.99
Total 115.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

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.