Financial Modeling for Algorithmic Trading using Python
3.9 (65 ratings)
Course Ratings are calculated from individual students’ ratings and a variety of other signals, like age of rating and reliability, to ensure that they reflect course quality fairly and accurately.
689 students enrolled

Financial Modeling for Algorithmic Trading using Python

A practical guide to implementing financial analysis strategies using Python
3.9 (65 ratings)
Course Ratings are calculated from individual students’ ratings and a variety of other signals, like age of rating and reliability, to ensure that they reflect course quality fairly and accurately.
689 students enrolled
Created by Packt Publishing
Last updated 3/2019
English [Auto-generated]
Current price: $129.99 Original price: $199.99 Discount: 35% off
2 hours left at this price!
30-Day Money-Back Guarantee
This course includes
  • 12.5 hours on-demand video
  • 1 downloadable resource
  • Full lifetime access
  • Access on mobile and TV
  • Certificate of Completion
Training 5 or more people?

Get your team access to 4,000+ top Udemy courses anytime, anywhere.

Try Udemy for Business
What you'll learn
  • How to use Numpy, Pandas, and matplotlib to manipulate, analyze, and visualize financial data
  • Understand the Time Value of Money applications and project selection
  • Make use of Monte Carlo method to simulate portfolio ending values, value options, and calculate Value at Risk
  • Understand complex financial terminology and methodology in simple ways
  • Featuring a premiere on Ensemble Learning with Bagging & Boosting
  • How to apply your skills to real world cryptocurrency trading such as Bitcoin and Ethereum
  • Building high-frequency trading robots
  • Implementing backtesting econometrics for trading strategies evaluation
  • Get hands-on with financial forecasting using machine learning with Python, Keras, scikit-learn, and pandas
Course content
Expand all 80 lectures 12:34:24
+ Hands-on Python for Finance
36 lectures 05:25:04

This video will give you an overview about the course.

Preview 02:58

In this video, we walk through installation of Anaconda, a popular scientific Python platform. The software is free to install and use.

   •  Download installation package

   •  Install software

   •  Verify installation

Installing the Anaconda Platform

In this video, we will briefly look at several Python interfaces.

   •  Demonstrate running programs and Python shell

   •  Demonstrate ipython, a more advanced interactive shell

   •  Demonstrate Jupyter Notebook the interface frequently use

Launching the Python Environment

In this video, introduce basic string functionality with an emphasis on formatting output

   •  Learn String definition and structure

   •  Use the format function

   •  Format output for presentation

String and Number Objects

In this video, we will talk about one of Python’s advanced data structures, the list.

   •  Learn about the list basics

   •  Access elements in a list

   •  Add, modify and delete elements

Python Lists

In this video, we will talk about one of Python’s advanced data structures, the dict.

   •  Learn about the structure of a dict, key/value pairs

   •  Access items in a dict

   •  Add, modify and delete elements

Python Dictionaries (Dicts)

In this video, we will introduce the idea of repletion in programs with the for loop; code blocks are also discussed.

   •  Learn about the For loop basics and code blocks

   •  Use the range function

   •  Combine for loop with formatting output

Repetition in Python (For Loops)

In this video, we will talk about making decisions in your program with the if..elif.. else blocks of code.

   •  Basic if statement block

   •  Use If with elif blocks

   •  Use If elif else full example

Branching Logic in Python (If Blocks)

In this video, we will talk about one creating reusable code with functions in Python.

   •  Encapsulatecomplex code in a function

   •  A simple function example with documentation string

   •  Access help on any function

Introduction to Functions in Python

In this video, we walk through the basics of the NumPy array data structure including creation, assessment and manipulation.

   •  Create sample arrays

   •  Determine size dimensions

   •  Display, manipulate and access data within an array

Introduction to NumPy Arrays

Continuing our introduction to NumPy with special placeholder arrays, mathematical operations and arrays created with random numbers.

   •  Demonstrate NumPy placeholder arrays

   •  Understand the examples of vectorized mathematical operations

   •  Introduce the NumPy random module

NumPy – A Deeper Dive

Introduction to the Pandas DataFrame data structure and common operations.

   •  Move from arrays into DataFrames

   •  Compare the two structures

   •  Learn about common operations in DataFrames

Pandas – Part I

Let’s dive deeper into the Pandas DataFrame data structure.

   •  Learn the mathematical operations

   •  Understand convenience functions

   •  Analyze the output

Pandas – Part II

Overview of common statistical methods available in the Scipy.stats module.

   •  Walkthrough several examples of statistical operations available

   •  Create a function for displaying summary statistics

Introduction to Scipy.stats

Introduction to the fundamental graphing library in Python: Matplotlib.

   •  Construct basic plots used in data analysis

   •  Learn basic line plots, scatter plots and histograms

Matplotlib – Part I

In this video, we will see how to add annotations and customize graphs.

   •  Start with a basic plot

   •  Add code to control the output

   •  Explore built-in graph styles

Matplotlib – Part II

In this video, we walk through the basics of calculating present value of single and multiple cashflows.

   •  Learn the basic example

   •  Create a present value function

   •  Value a stream of future cashflows today

Present Value of a Stream of Cash Flows

In this video, we will discuss future value concepts of fixed and uncertain rates of return. The video ends with an introduction to NumPy built-in functions for time value of money calculations.

   •  Learn the basic example

   •  Create a future value function

   •  Value current holdings with constant and uncertain returns

Future Value of Single and Multiple Cash Flows

Introduction to comparing capital budgeting projects with net present value

   •  Manually calculate net present value

   •  Compare manual method with NumPy’s built-in function

   •  Create the respective model for same

Net Present Value of a Project

In this video, we will get a comparison and relationship of net present value to internal rate of return.

   •  Use NumPy’s built-in IRR function

   •  Compare IRR to NPV

   •  Understand testing functionality and output

Internal Rate of Return

Walkthrough of enumeration of retiring long term debt in the form a table that tracks loan balance, interest and principal payments and cumulative interest paid

   •  Demonstrate the NumPypmt function to calculate monthly payments

   •  Build Pandas DataFrame to store relevant loan outputs

   •  Graph loan balance and cumulative interest over time

Introduction to Amortization

In this video, use parts of the previous video to create a reusable amortization application allowing users to compare loan scenarios.

   •  Create a function that outputs amortization table and loan summary data

   •  Compare several loan scenarios to demonstrate functionality

Creating an Amortization Application

In this video, we see how to open and work with data stored in CSV files.

   •  Demonstrate several methods of accessing data stored in CSV files

   •  Focus where images will be stored

   •  Analyze the data attributes

Opening and Reading a .CSV File

We introduce the pandasdatareader library and use it to download and manipulate data.

   •  Download data from Yahoo finance

   •  Learn data transformations

   •  Understand data visualization

Getting and Evaluating Data

In this video we learn how to create and evaluate a moving average forecasting model.

   •  Create a moving average forecasting model with downloaded data

   •  Evaluate the forecasting model

   •  All the images will be saved in datasets folder

Moving Average Forecasting

In this video, we will introduce another library’ statsmodels, and use its built-in single exponential smoothing model.

   •  Use statsmodels exponential smoothing model to forecast the price of gold

   •  Demonstrate the model with various values of a smoothing constant

Forecasting with Single Exponential Smoothing

In this video, we will develop a simple signals based trading system and back test it for effectiveness.

   •  Create a fast and slow moving average forecast

   •  Create a signal and system return column

   •  Compare visually, the trading system to buy and hold strategy

Creating and Testing a Simple Trading System

In this video, we introduce basic models for stock valuation.

   •  Calculate expected return

   •  Value securities using dividends and expected future value

   •  Value security using PE ratio

Valuing Securities with Pricing Models

Securities have a tendency to move together to some degree. This video demonstrates how to measure this relationship numerically and visually.

   •  Download data from Yahoo finance

   •  Data transformations

   •  Create table of correlations and graph relationships

Finding Correlations Between Securities

Some variables have predictive power over others. In this video, we demonstrate and interpret a simple linear regression model with two libraries.

   •  Open and clean dataset

   •  Examine relationship with scatter plot

   •  Create linear model and use it to predict specific values

Linear Regression

Beta is used as a simple measurement of a stock’s riskiness relative to the market as a whole. This video derives Beta using two distinct methods.

   •  Download market and security data

   •  Transform data

   •  Calculate Beta with linear regression and with NumPycov function

Calculating Beta and Expected Return

Diversification can mute risk in the stock market. This video demonstrates the impact of diversification with a two security portfolio.

   •  Calculate expected return and volatility of a two security portfolio

   •  Create table with various weights, returns and volatilities

   •  Graph volatility vs. expected return

Constructing Portfolios Along the Efficient Frontier

In this video, compare deterministic ending values with probabilistic ending values of a portfolio.

   •  Calculate table of ending values

   •  Calculate table of ending values based on probability distribution

   •  Analyze the data attributes and environmental setup of Keras

Introduction to Monte Carlo

In this video, we will create a full simulation and examine results.

   •  Create NumPy array to store returns

   •  Create NumPy array to store yearly ending values

   •  Run simulation and examine results

Monte Carlo Simulation

In this video, explore Value at Risk, calculate parametric VaR with simple formula and via Monte Carlo simulation.

   •  Calculate VaR deterministically

   •  Calculate VaR using Monte Carlo method

   •  Analyze the output

Using Monte Carlo Technique to Calculate Value at Risk

In this video, put concepts discussed in previous videos together in a module that can be imported and used in encapsulated form.

   •  Combine methods of previous videos into functions of MonteCarlo class

   •  Demonstrate functionality

   •  The list of data will be evaluated in respective chart

Putting It All Together – Monte Simulation Application
Test your knowledge
5 questions
+ Machine Learning for Algorithmic Trading Bots with Python
26 lectures 04:50:02

This video will give you an overview about the course.

Preview 04:18

In this video, you will become familiar with the basics of trading, economics, and finance required to start building high-frequency trading algorithms.

  • Explain Financial Terminology

  • Explain Micro-market Structure

  • Explain Financial Data Structures

Introduction to Financial Machine Learning and Algorithmic Trading

In this video, you shall setup your machine / virtual machine so that you could start building algorithmic trading bots in subsequent sections.

  • Setup Linux OS / Virtual Machine

  • Setup Python Development Environment including Anaconda & Zipline

  • Setup and Customize Eclipse IDE for Python including Git Plugins

Setting up the Environment

In this video, you shall build the essential components of a generic trading strategy, and you will integrate it with Zipline / Quantopian APIs.

  • Build Empty trading strategy following Zipline / Quantopian Interface

  • Implement & Configure Zipline run_algorithm method

Project Skeleton Overview

In this video, you are going to analyze the pricing data using Jupyter Notebook. You will also plot the historical pricing data and interpret the trends observed.

  • Download Zipline Data Bundles Quandl / Quantopian-Quandl

  • Fetch Data using Zipline Data Portal Interface

  • Plot and Chart the Pricing Data using Matplotlib and analyze Candle Stick Charts

Fetching and Understanding the Dataset

In this video, you’re going to build your first trading strategy and integrate it into your trading bot.

  • Understand the Buy & Hold Strategy

  • Implement the Buy & Hold Strategy

  • Integrate the Buy & Hold Strategy into the Trading Bot

Build the Conventional Buy and Hold Strategy

In this video, you will analyze the performance reports outputted by Zipline Backtesting. You are going to plot charts of economic evaluation metrics using Matplotlib.

  • Load the Performance Report of the Buy & Hold Strategy.

  • Analyze and Interpret the different evaluation metrics of the Backtesting

  • Calculate the Return on Investment ( ROI ) and Understand the Dynamics of Stock Splits

Evaluate the Strategy’s Performance

In this video, you will become familiar with the basics of decision trees, random forests, and ensemble learning.

  • Study the mathematics and algorithm criteria for building decision trees

  • Introduce ensemble learning bootstrap aggregation (bagging)

  • Highlight the difference between classification and regression trees

Intuition behind Random Forests Algorithm

In this video, you shall learn how to implement random forests for stock price forecasting using SciKit-Learn machine learning library in Python.

  • Feature engineering for stock price model

  • Fine-tuning the parameters of Random Forests Regressor model

  • Train and export the model using JobLib

Build and Implement Random Forests Algorithm

In this video, you shall integrate the trained model into the existing trading bot skeletion and learn how to import models and use them forecasting during a trading session.

  • Import trained random forests Regressor model

  • Design a trading strategy that forecasts stock price before making decisions

  • Run the Backtest session

Plug-in Random Forests Implementation into Your Bot

In this video, you are going to analyze the Backtest session performance report using Jupyter Notebook. You will learn new econometric fundamentals and understand the different evaluation metrics.

  • Import the performance report in a Jupyter Notebook

  • Plot and analyze performance

  • Understand econometric evaluation metrics available in Zipline

Evaluate Random Forest’s Performance

In this video, you will become familiar with the basics of online streaming algorithms and learn the mechanisms of the one-pass algorithms.

  • Explain online algorithms terminology, basics, advantages, and requirements

  • Understand the mechanism of one-pass algorithms

Introducing Online Algorithms

In this video, you shall learn correlation analysis in statistics, auto-correlation trading strategy, and pairs trading strategy.

  • Dive into the mathematics of correlation analysis

  • Learn how the auto-correlation trading strategy works

  • Learn how the pairs trading strategy works

Getting Statistical Correlation

In this video, you shall build the auto-correlation trading strategy into our algorithmic trading bot and learn more about the Zipline APIs.

  • Design and implement the Auto-Correlation Strategy with Python

  • Configure Zipline run_algorithm method

  • Run the strategy and plot portfolio value over time

Implement Exploit Correlation Strategy

In this video, you are going to analyze the performance reports using Jupyter Notebook. You will also learn more econometric evaluation methods and techniques.

  • Import the performance report

  • Analyze and plot econometric indicators

  • Understand the interpretation of more econometric indicators and what each one of them means

Evaluate the Strategy

In this video, you will become familiar with the basics of boosting, gradient boosting, and time series cross validation.

  • What is boosting in ensemble learning?

  • What is gradient boosting and how is it related to gradient descent?

  • What is cross validation? Introduce variants of cross validation for time series forecasting.

Ensemble Learning Theory

In this video, you shall implement gradient boosting using SciKit-Learn with Time Series Split.

  • Feature engineering of price model data using Pandas

  • Implement time series cross validation with SciKit-Learn

  • Train and export a gradient boosting model

Implementing GBoosting Using Python

In this video, you shall understand the evaluation metrics for machine learning models with cross validation.

  • Evaluate cross validation loss and accuracy

  • Visualize train test splits for SciKit-Learn time series split

Evaluating the Model Performance

In this video, you will become familiar with the basics of scalp trading and indicators signals.

  • What is scalp trading?

  • How to implement scalp trading with indicator signals and bollinger bands?

  • What is Sharpe Ratio?

Introduction to Scalpers Trading Strategy

In this video, you shall implement scalp trading with two indicator signals and bollinger bands.

  • Implement scalp trading class

  • Import BitCoin and Ethereum securities custom dataset into Zipline

  • Run Backtest session for scalp trading with custom dataset

Implement Scalpers Trading Strategy

In this video, you shall understand the evaluation metrics for investment portfolio with Sharpe Ratio.

  • Import performance report using Pandas and analyze econometric signals

  • Analyze and visualize Sharpe Ratio

  • Analyze and visualize accumulative returns

Evaluate Scalpers Trading Strategy

In this video, you will learn risk management fundamentals and how to calculate Value at Risk.

  • Risk management process

  • How to trigger Stop loss

  • How to calculate VaR

Introducing Value at Risk Backtest

In this video, you shall integrate VaR & stop loss into scalp trading with two indicator signals and bollinger bands.

  • A quick refresher on historical simulation and model-based approaches to calculate VaR

  • Calculate Conditional Value at Risk in Zipline trading sessions of Backtest simulation.

  • Trigger stop loss and exit positions

Implement Value at Risk Backtest

In this video, we introduce support vector machines for both classification and regression, and how to use different kernel functions such as sigmoid and radial basis functions.

  • Support Vector Machine and finding an optimal decision boundary

  • Kernel functions and the difference between linearly separable and non-linearly separable datasets

  • The mathematics derivation of support vector machines as primal dual optimization problem with Lagrange multipliers

Value at Risk with Machine Learning

In this video, you will code along the implementation of support vector regression with grid search cross validation for forecasting portfolio returns.

  • Implement support vector regression and grid search cross validation with SciKit-Learn

  • Import trained model and forecast portfolio returns during Zipline Backtest simulation

  • Evaluate the Sharpe ratio and accumulative returns of the trading strategy

Implement VaR Using SVR

In this video, I bid you a farewell and give you some career hints for future applications of techniques learned throughout the course.

  • Reference text books on financial machine learning

  • Machine learning potentials in finance

  • Your first internship goals and culture hints

Conclusion and Next steps
Test your knowledge
5 questions
+ AI for Finance
18 lectures 02:19:18

This video gives a glimpse of the entire course.

Preview 05:36

Define what we mean by financial forecasting, what AI methods we will be using in this course and how they solve common problems in Finance.

  • Learn the basic definition of financial forecasting

  • Learn which AI methods we will be focusing on in this course

  • Learn how those methods help solving one of the most challenging problems in Finance

What’s Financial Forecasting and Why It’s Important?

Learn how to quickly install and verify all the necessary tools to work with financial data and AI methods.

  • Download, install, and verify Miniconda package manager and Python 3.7 distribution

  • Install all the necessary packages using Conda

  • Verify that they have been installed correctly

Installing Pandas, Scikit-Learn, Keras, and TensorFlow

Sum up what we’ve learned in this section.

  • The intuition behind financial forecasting

  • Understanding why forecasting is a fundamental tool in Finance

  • Learn how to quickly install all the necessary tools to work with AI methods and financial data


Learn where you can download the free stock prices data and how to convert for forecasting with a MLP Model.

  • Locate and download the free stock prices data

  • Explore the dataset

  • Shape dataset into a supervised learning problem

Getting and Preparing the Currency Exchange Data

Understand how to build a MLP Model for forecasting step by step.

  • Learn the main container, input, and output of each MLP Model

  • Learn how to add a hidden layer into an MLP Model

  • Explore how to pick up the right loss function and optimizer and how to compile the model

Building the MLP Model with Keras

Learn the steps behind training and testing the MLP Model.

  • Understand the key metrics in training and testing the model

  • Learn when it’s a good time to stop training the model for optimal results

  • Learn how use the training script and interpret the training results

Training and Testing the Model

Summarize what you’ve learned in this section.

  • Understand the big picture being using a MLP Model for financial forecasting

  • Learn where you can find the free stock prices data and how to prepare it for the MLP Model

  • Explore the training process of the MLP Model step by step

Summary and What’s Next?

Learn where to get the rare loan financial dataset for free and how to shape it for our model.

  • Locate and download the dataset

  • Explore the dataset

  • Encode the dataset for our classifier

Getting and Preparing the Loan Approval Data

Understand how to create a gradient boosted classifier in Scikit-Learn, train and evaluate the model.

  • Create a new classifier

  • Evaluate the classifier using our dataset and cross validation method

  • Use our model on a new dataset

Creating, Training, Testing, and Using a GradientBoostingClassfier Model

Summarize what you’ve learned in this section.

  • Understand the high level of the problem

  • Learn where you can get the problem dataset and how to use it for forecasting

  • Build and evaluate the model, use it for forecasting with a new data

Summary and What’s Next?

Find the rare financial data and learn how to use with detecting frauds.

  • Locate and download the data

  • Explore the dataset

  • Clean up and encode dataset for optimal results

Getting and Preparing Financial Fraud Data

Learn how to create, train and test a new model that is able to deal with an imbalanced dataset.

  • Create and configure a new classifier in Scikit-Learn for an imbalanced dataset

  • Train the new model

  • Evaluate the model using a test set

Creating, Training, and Testing XGBoost Model

Summarize what you’ve learned in this section.

  • Understand the main steps in detecting fraud in financial data

  • Explore the fraud dataset

  • Learn how build, train, and test the model for fraud detection

Summary and What’s Next?

Find out where you can get the free sock prices data and how to format it for LSTM.

  • Locate and download the free stock prices data, put it in the right place

  • Explore the dataset

  • Create a supervised learning problem dataset

Getting and Preparing the Stock Prices Data

Understand the main steps to create a LSTM model in Keras.

  • Understand the main model container and it’s input and output

  • Learn how to configure a LSTM hidden layer

  • Pick up the right parameters to compile the model

Building the LSTM Model with Keras

Learn the basics of training and testing the LSTM Model.

  • Understand the main training parameters like batch-size and epoch, pick up the right values

  • Understand the training and testing metrics and how to use them to find out when to stop training

  • Learn how to run the training script and interpret results

Training and Testing the Model

Summarize what you’ve learned in this section.

  • Understand the main goal of this section

  • Learn where to get the data and how to use it

  • Learn how to train a LSTM network with our dataset

Summary and What’s Next?
Test your knowledge
4 questions
  • Working knowledge of Python is required.

Video Learning Path Overview

A Learning Path is a specially tailored course that brings together two or more different topics that lead you to achieve an end goal. Much thought goes into the selection of the assets for a Learning Path, and this is done through a complete understanding of the requirements to achieve a goal.

Technology has become an asset in finance. Among the hottest programming languages, you’ll find Python becoming the technology of choice for Finance. The financial industry is increasingly adopting Python for general-purpose programming and quantitative analysis, ranging from understanding trading dynamics to building financial machine learning models.

This well thought out Learning Path takes a step by step approach to teach you how to use Python for performing financial analysis and modeling on a day-to-day basis. Beginning with an introduction to Python and its third party libraries, you will learn how to apply basics of Finance such as Time Value of Money and time series in Python. You will also perform valuations, linear regressions, and Monte Carlo simulation for analyzing some basic models.

Once you are comfortable in analyzing models with Python, you will learn to practically apply them to analyze machine learning models for your own financial data. You will then learn how to build machine learning models and trading algorithms as per your trade. You will also learn to build a trading bot for providing fully automated trading solutions to your trade. Next, you will learn to evaluate the models for value at risk using machine learning techniques.

Now that you are being familiar with machine learning, you will step ahead with learning deep learning techniques for Financial forecasting, predicting Forex currency exchange rates, looking into financial loan approval, fraud detection, and forecasting stock prices.

Towards the end of this course, you will be able to perform financial valuations, build algorithmic trading bots, and perform stock trading and financial analysis in different areas of finance.

Key Features

  • Get hands-on with financial forecasting using machine learning with Python, Keras, scikit-learn, and pandas

  • Use libraries like Numpy, Pandas, Scipy and Matplotlib for data analysis, manipulation and visualization

  • Be comfortable with Monte Carlo Simulation, Value at Risk, and Options Valuation

  • Grasp Machine Learning forecasting on a specific real-world financial data

Author Bios

  • Matthew Macarty has taught graduate and undergraduate business school students for over 15 years and currently teaches at Bentley University. He has taught courses in statistics, quantitative methods, information systems and database design.

  • Mustafa Qamar-ud-Din is a machine learning engineer with over 10 years of experience in the software development industry. He is a specialist in image processing, machine learning and deep learning. He worked with many startups and understands the dynamics of agile methodologies and the challenges they face on a day to day basis. He is also quite aware of the professional skills which the recruiters are looking for when making hiring decisions.

  • Jakub Konczyk has enjoyed and done programming professionally since 1995. He is a Python and Django expert and has been involved in building complex systems since 2006. He loves to simplify and teach programming subjects and share it with others. He first discovered Machine Learning when he was trying to predict the real estate prices in one of the early stage startups he was involved in. He failed miserably. Then he discovered a much more practical way to learn Machine Learning that he would like to share with you in this course. It boils down to “Keep it simple!” mantra.

Who this course is for:
  • This course is ideal for aspiring data scientists, Python developers and anyone who wants to start performing quantitative finance using Python. You can also make this beginner-level guide your first choice if you’re looking to pursue a career as a financial analyst or a data analyst.