Mastering Python for Finance - Second Edition

Book description

Take your financial skills to the next level by mastering cutting-edge mathematical and statistical financial applications

Key Features

  • Explore advanced financial models used by the industry and ways of solving them using Python
  • Build state-of-the-art infrastructure for modeling, visualization, trading, and more
  • Empower your financial applications by applying machine learning and deep learning

Book Description

The second edition of Mastering Python for Finance will guide you through carrying out complex financial calculations practiced in the industry of finance by using next-generation methodologies. You will master the Python ecosystem by leveraging publicly available tools to successfully perform research studies and modeling, and learn to manage risks with the help of advanced examples.

You will start by setting up your Jupyter notebook to implement the tasks throughout the book. You will learn to make efficient and powerful data-driven financial decisions using popular libraries such as TensorFlow, Keras, Numpy, SciPy, and scikit-learn. You will also learn how to build financial applications by mastering concepts such as stocks, options, interest rates and their derivatives, and risk analytics using computational methods. With these foundations, you will learn to apply statistical analysis to time series data, and understand how time series data is useful for implementing an event-driven backtesting system and for working with high-frequency data in building an algorithmic trading platform. Finally, you will explore machine learning and deep learning techniques that are applied in finance.

By the end of this book, you will be able to apply Python to different paradigms in the financial industry and perform efficient data analysis.

What you will learn

  • Solve linear and nonlinear models representing various financial problems
  • Perform principal component analysis on the DOW index and its components
  • Analyze, predict, and forecast stationary and non-stationary time series processes
  • Create an event-driven backtesting tool and measure your strategies
  • Build a high-frequency algorithmic trading platform with Python
  • Replicate the CBOT VIX index with SPX options for studying VIX-based strategies
  • Perform regression-based and classification-based machine learning tasks for prediction
  • Use TensorFlow and Keras in deep learning neural network architecture

Who this book is for

If you are a financial or data analyst or a software developer in the financial industry who is interested in using advanced Python techniques for quantitative methods in finance, this is the book you need! You will also find this book useful if you want to extend the functionalities of your existing financial applications by using smart machine learning techniques. Prior experience in Python is required.

Table of contents

  1. Title Page
  2. Copyright and Credits
    1. Mastering Python for Finance Second Edition
  3. Dedication
  4. Contributors
    1. About the author
    2. About the reviewers
    3. Packt is searching for authors like you
  5. About Packt
    1. Why subscribe?
    2. Packt.com
  6. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  7. Section 1: Getting Started with Python
  8. Overview of Financial Analysis with Python
    1. Getting Python
      1. Preparing a virtual environment
      2. Running Jupyter Notebook
      3. The Python Enhancement Proposal
        1. What is a PEP?
        2. The Zen of Python
    2. Introduction to Quandl
      1. Setting up Quandl for your environment
    3. Plotting a time series chart
      1. Retrieving datasets from Quandl
      2. Plotting a price and volume chart
      3. Plotting a candlestick chart
    4. Performing financial analytics on time series data
      1. Plotting returns
      2. Plotting cumulative returns
      3. Plotting a histogram
      4. Plotting volatility
      5. A quantile-quantile plot
      6. Downloading multiple time series data
      7. Displaying the correlation matrix
      8. Plotting correlations
      9. Simple moving averages
      10. Exponential moving averages
    5. Summary
  9. Section 2: Financial Concepts
  10. The Importance of Linearity in Finance
    1. The Capital Asset Pricing Model and the security market line
    2. The Arbitrage Pricing Theory model
    3. Multivariate linear regression of factor models
    4. Linear optimization
      1. Getting Pulp
      2. A maximization example with linear programming
      3. Outcomes of linear programs
      4. Integer programming
        1. A minimization example with integer programming
        2. Integer programming with binary conditions
    5. Solving linear equations using matrices
    6. The LU decomposition
    7. The Cholesky decomposition
    8. The QR decomposition
    9. Solving with other matrix algebra methods
      1. The Jacobi method
      2. The Gauss-Seidel method
    10. Summary
  11. Nonlinearity in Finance
    1. Nonlinearity modeling
      1. Examples of nonlinear models
        1. The implied volatility model
        2. The Markov regime-switching model
        3. The threshold autoregressive model
        4. Smooth transition models
    2. Root-finding algorithms
      1. Incremental search
      2. The bisection method
      3. Newton's method
      4. The secant method
      5. Combing root-finding methods
    3. SciPy implementations in root-finding
      1. Root-finding scalar functions
      2. General nonlinear solvers
    4. Summary
  12. Numerical Methods for Pricing Options
    1. Introduction to options
    2. Binomial trees in option pricing
    3. Pricing European options
    4. Writing the StockOption base class
      1. A class for European options using a binomial tree
      2. A class for American options using a binomial tree
      3. The Cox–Ross–Rubinstein model
        1. A class for the CRR binomial tree option pricing model
      4. Using a Leisen-Reimer tree
        1. A class for the LR binomial tree option pricing model
    5. The Greeks for free
      1. A class for Greeks with the LR binomial tree
    6. Trinomial trees in option pricing
      1. A class for the trinomial tree option pricing model
    7. Lattices in option pricing
      1. Using a binomial lattice
      2. A class for the CRR binomial lattice option pricing model
      3. Using the trinomial lattice
        1. A class for the trinomial lattice option pricing model
    8. Finite differences in option pricing
      1. The explicit method
      2. Writing the finite difference base class
        1. A class for pricing European options using the explicit method of finite differences
      3. The implicit method
        1. A class for pricing European options using the implicit method of finite differences
      4. The Crank-Nicolson method
        1. A class for pricing European options using the Crank-Nicolson method of finite differences
      5. Pricing exotic barrier options
        1. A down-and-out option
        2. A class for pricing down-and-out-options using the Crank-Nicolson method of finite differences
      6. Pricing American options with finite differences
        1. A class for pricing American options using the Crank-Nicolson method of finite differences
    9. Putting it all together – implied volatility modeling
      1. Implied volatilities of the AAPL American put option
    10. Summary
  13. Modeling Interest Rates and Derivatives
    1. Fixed-income securities
    2. Yield curves
    3. Valuing a zero-coupon bond
      1. Spot and zero rates
    4. Bootstrapping a yield curve
      1. An example of bootstrapping the yield curve
      2. Writing the yield curve bootstrapping class
    5. Forward rates
    6. Calculating the yield to maturity
    7. Calculating the price of a bond
    8. Bond duration
    9. Bond convexity
    10. Short–rate modeling
      1. The Vasicek model
      2. The Cox-Ingersoll-Ross model
      3. The Rendleman and Bartter model
      4. The Brennan and Schwartz model
    11. Bond options
      1. Callable bonds
      2. Puttable bonds
      3. Convertible bonds
      4. Preferred stocks
    12. Pricing a callable bond option
      1. Pricing a zero-coupon bond by the Vasicek model
      2. The value of early exercise
      3. Policy iteration by finite differences
      4. Other considerations in callable bond pricing
    13. Summary
  14. Statistical Analysis of Time Series Data
    1. The Dow Jones industrial average and its 30 components
      1. Downloading Dow component datasets from Quandl
      2. About Alpha Vantage
      3. Obtaining an Alpha Vantage API key
      4. Installing the Alpha Vantage Python wrapper
      5. Downloading the DJIA dataset from Alpha Vantage
    2. Applying a kernel PCA
      1. Finding eigenvectors and eigenvalues
      2. Reconstructing the Dow index with PCA
    3. Stationary and non-stationary time series
      1. Stationarity and non-stationarity
      2. Checking for stationarity
      3. Types of non-stationary processes
      4. Types of stationary processes
    4. The Augmented Dickey-Fuller Test
    5. Analyzing a time series with trends
    6. Making a time series stationary
      1. Detrending
      2. Removing trend by differencing
      3. Seasonal decomposing
      4. Drawbacks of ADF testing
    7. Forecasting and predicting a time series
      1. About the Autoregressive Integrated Moving Average
      2. Finding model parameters by grid search
      3. Fitting the SARIMAX model
      4. Predicting and forecasting the SARIMAX model
    8. Summary
  15. Section 3: A Hands-On Approach
  16. Interactive Financial Analytics with the VIX
    1. Volatility derivatives
      1. STOXX and the Eurex
      2. The EURO STOXX 50 Index
      3. The VSTOXX
      4. The S&P 500 Index
      5. SPX options
      6. The VIX
    2. Financial analytics of the S&P 500 and the VIX
      1. Gathering the data
      2. Performing analytics
      3. The correlation between the SPX and the VIX
    3. Calculating the VIX Index
      1. Importing SPX options data
        1. Parsing SPX options data
      2. Finding near-term and next-term options
      3. Calculating the required minutes
      4. Calculating the forward SPX Index level
      5. Finding the required forward strike prices
      6. Determining strike price boundaries
      7. Tabulating contributions by strike prices
      8. Calculating the volatilities
      9. Calculating the next-term options
      10. Calculating the VIX Index
      11. Calculating multiple VIX indexes
      12. Comparing the results
    4. Summary
  17. Building an Algorithmic Trading Platform
    1. Introducing algorithmic trading
      1. Trading platforms with a public API
      2. Choosing a programming language
      3. System functionalities
    2. Building an algorithmic trading platform
      1. Designing a broker interface
      2. Python library requirements
        1. Installing v20
      3. Writing an event-driven broker class
      4. Storing the price event handler
      5. Storing the order event handler
      6. Storing the position event handler
      7. Declaring an abstract method for getting prices
      8. Declaring an abstract method for streaming prices
      9. Declaring an abstract method for sending orders
      10. Implementing the broker class
        1. Initializing the broker class
        2. Implementing the method for getting prices
        3. Implementing the method for streaming prices
        4. Implementing the method for sending market orders
        5. Implementing the method for fetching positions
        6. Getting the prices
        7. Sending a simple market order
        8. Getting position updates
    3. Building a mean-reverting algorithmic trading system
      1. Designing the mean-reversion algorithm
      2. Implementing the mean-reversion trader class
      3. Adding event listeners
      4. Writing the mean-reversion signal generators
      5. Running our trading system
    4. Building a trend-following trading platform
      1. Designing the trend-following algorithm
      2. Writing the trend-following trader class
      3. Writing the trend-following signal generators
      4. Running the trend-following trading system
    5. VaR for risk management
    6. Summary
  18. Implementing a Backtesting System
    1. Introducing backtesting
      1. Concerns in backtesting
      2. Concept of an event-driven backtesting system
    2. Designing and implementing a backtesting system
      1. Writing a class to store tick data
      2. Writing a class to store market data
      3. Writing a class to generate sources of market data
      4. Writing the order class
      5. Writing a class to keep track of positions
      6. Writing an abstract strategy class
      7. Writing a mean-reverting strategy class
      8. Binding our modules with a backtesting engine
      9. Running our backtesting engine
      10. Multiple runs of the backtest engine
      11. Improving your backtesting system
    3. Ten considerations for a backtesting model
      1. Resources restricting your model
      2. Criteria of evaluation of the model
      3. Estimating the quality of backtest parameters
      4. Be prepared to face model risk
      5. Performance of a backtest with in–sample data
      6. Addressing common pitfalls in backtesting
      7. Have a common-sense idea of your model
      8. Understanding the context for the model
      9. Make sure you have the right data
      10. Data mine your results
    4. Discussion of algorithms in backtesting
      1. K-means clustering
      2. K-nearest neighbors machine learning algorithm
      3. Classification and regression tree analysis
      4. The 2k factorial design
      5. The genetic algorithm
    5. Summary
  19. Machine Learning for Finance
    1. Introduction to machine learning
      1. Uses of machine learning in finance
        1. Algorithmic trading
        2. Portfolio management
        3. Supervisory and regulatory functions
        4. Insurance and loan underwriting
        5. News sentiment analysis
        6. Machine learning beyond finance
      2. Supervised and unsupervised learning
        1. Supervised learning
        2. Unsupervised learning
      3. Classification and regression in supervised machine learning
      4. Overfitting and underfitting models
      5. Feature engineering
      6. Scikit-learn for machine learning
    2. Predicting prices with a single-asset regression model
      1. Linear regression by OLS
      2. Preparing the independent and target variables
      3. Writing the linear regression model
      4. Risk metrics for measuring prediction performance
        1. Mean absolute error as a risk metric
        2. Mean squared error as a risk metric
        3. Explained variance score as a risk metric
        4. R2 as a risk metric
      5. Ridge regression
      6. Other regression models
        1. Lasso regression
        2. Elastic net
      7. Conclusion
    3. Predicting returns with a cross-asset momentum model
      1. Preparing the independent variables
      2. Preparing the target variables
      3. A multi-asset linear regression model
      4. An ensemble of decision trees
        1. Bagging regressor
        2. Gradient tree boosting regression model
        3. Random forests regression
        4. More ensemble models
    4. Predicting trends with classification-based machine learning
      1. Preparing the target variables
      2. Preparing the dataset of multiple assets as input variables
      3. Logistic regression
      4. Risk metrics for measuring classification-based predictions
        1. Confusion matrix
        2. Accuracy score
        3. Precision score
        4. Recall score
        5. F1 score
      5. Support vector classifier
      6. Other types of classifiers
        1. Stochastic gradient descent
        2. Linear discriminant analysis
        3. Quadratic discriminant analysis
        4. KNN classifier
    5. Conclusion on the use of machine learning algorithms
    6. Summary
  20. Deep Learning for Finance
    1. A brief introduction to deep learning
      1. What is deep learning ?
      2. The artificial neuron
      3. Activation function
      4. Loss functions
      5. Optimizers
      6. Network architecture
      7. TensorFlow and other deep learning frameworks
      8. What is a tensor ?
    2. A deep learning price prediction model with TensorFlow
      1. Feature engineering our model
      2. Requirements
        1. Intrinio as our data provider
        2. Compatible Python environment for TensorFlow
        3. The requests library
        4. The TensorFlow library
      3. Downloading the dataset
      4. Scaling and splitting the data
      5. Building an artificial neural network with TensorFlow
        1. Phase 1 – assembling the graph
        2. Phase 2 – training our model
      6. Plotting predicted and actual values
    3. Credit card payment default prediction with Keras
      1. Introduction to Keras
      2. Installing Keras
      3. Obtaining the dataset
      4. Splitting and scaling the data
      5. Designing a deep neural network with five hidden layers using Keras
      6. Measuring the performance of our model
        1. Running risk metrics
      7. Displaying recorded events in Keras history
    4. Summary
  21. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: Mastering Python for Finance - Second Edition
  • Author(s): James Ma Weiming
  • Release date: April 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781789346466