Python for Finance - Second Edition

Book description

Learn and implement various Quantitative Finance concepts using the popular Python libraries

About This Book

  • Understand the fundamentals of Python data structures and work with time-series data

  • Implement key concepts in quantitative finance using popular Python libraries such as NumPy, SciPy, and matplotlib

  • A step-by-step tutorial packed with many Python programs that will help you learn how to apply Python to finance

  • Who This Book Is For

    This book assumes that the readers have some basic knowledge related to Python. However, he/she has no knowledge of quantitative finance. In addition, he/she has no knowledge about financial data.

    What You Will Learn

  • Become acquainted with Python in the first two chapters

  • Run CAPM, Fama-French 3-factor, and Fama-French-Carhart 4-factor models

  • Learn how to price a call, put, and several exotic options

  • Understand Monte Carlo simulation, how to write a Python program to replicate the Black-Scholes-Merton options model, and how to price a few exotic options

  • Understand the concept of volatility and how to test the hypothesis that volatility changes over the years

  • Understand the ARCH and GARCH processes and how to write related Python programs

  • In Detail

    This book uses Python as its computational tool. Since Python is free, any school or organization can download and use it.

    This book is organized according to various finance subjects. In other words, the first edition focuses more on Python, while the second edition is truly trying to apply Python to finance.

    The book starts by explaining topics exclusively related to Python. Then we deal with critical parts of Python, explaining concepts such as time value of money stock and bond evaluations, capital asset pricing model, multi-factor models, time series analysis, portfolio theory, options and futures.

    This book will help us to learn or review the basics of quantitative finance and apply Python to solve various problems, such as estimating IBM’s market risk, running a Fama-French 3-factor, 5-factor, or Fama-French-Carhart 4 factor model, estimating the VaR of a 5-stock portfolio, estimating the optimal portfolio, and constructing the efficient frontier for a 20-stock portfolio with real-world stock, and with Monte Carlo Simulation. Later, we will also learn how to replicate the famous Black-Scholes-Merton option model and how to price exotic options such as the average price call option.

    Style and approach

    This book takes a step-by-step approach in explaining the libraries and modules in Python, and how they can be used to implement various aspects of quantitative finance. Each concept is explained in depth and supplemented with code examples for better understanding.

    Table of contents

    1. Python for Finance Second Edition
      1. Table of Contents
      2. Python for Finance Second Edition
      3. Credits
      4. About the Author
      5. About the Reviewers
      6. www.PacktPub.com
        1. eBooks, discount offers, and more
          1. Why subscribe?
      7. Customer Feedback
      8. Preface
        1. A few words for the second edition
        2. Why Python?
        3. A programming book written by a finance professor
        4. What this book covers
        5. Small-program oriented
        6. Using real-world data
        7. What you need for this book
        8. Who this book is for
        9. Conventions
        10. Reader feedback
        11. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      9. 1. Python Basics
        1. Python installation
          1. Installation of Python via Anaconda
          2. Launching Python via Spyder
          3. Direct installation of Python
        2. Variable assignment, empty space, and writing our own programs
        3. Writing a Python function
        4. Python loops
          1. Python loops, if...else conditions
        5. Data input
        6. Data manipulation
        7. Data output
        8. Exercises
        9. Summary
      10. 2. Introduction to Python Modules
        1. What is a Python module?
        2. Introduction to NumPy
        3. Introduction to SciPy
        4. Introduction to matplotlib
          1. How to install matplotlib
          2. Several graphical presentations using matplotlib
        5. Introduction to statsmodels
        6. Introduction to pandas
        7. Python modules related to finance
        8. Introduction to the pandas_reader module
        9. Two financial calculators
        10. How to install a Python module
        11. Module dependency
        12. Exercises
        13. Summary
      11. 3. Time Value of Money
        1. Introduction to time value of money
        2. Writing a financial calculator in Python
        3. Definition of NPV and NPV rule
        4. Definition of IRR and IRR rule
        5. Definition of payback period and payback period rule
        6. Writing your own financial calculator in Python
        7. Two general formulae for many functions
          1. Appendix A – Installation of Python, NumPy, and SciPy
          2. Appendix B – visual presentation of time value of money
          3. Appendix C – Derivation of present value of annuity from present value of one future cash flow and present value of perpetuity
          4. Appendix D – How to download a free financial calculat
          5. Appendix E – The graphical presentation of the relationship between NPV and R
          6. Appendix F – graphical presentation of NPV profile with two IRRs
          7. Appendix G – Writing your own financial calculator in Python
        8. Exercises
        9. Summary
      12. 4. Sources of Data
        1. Diving into deeper concepts
          1. Retrieving data from Yahoo!Finance
          2. Retrieving data from Google Finance
          3. Retrieving data from FRED
          4. Retrieving data from Prof. French's data library
          5. Retrieving data from the Census Bureau, Treasury, and BLS
          6. Generating two dozen datasets
          7. Several datasets related to CRSP and Compustat
            1. Appendix A – Python program for return distribution versus a normal distribution
            2. Appendix B – Python program to a draw candle-stick picture
            3. Appendix C – Python program for price movement
            4. Appendix D – Python program to show a picture of a stock's intra-day movement
            5. Appendix E –properties for a pandas DataFrame
            6. Appendix F –how to generate a Python dataset with an extension of .pkl or .pickle
            7. Appendix G – data case #1 -generating several Python datasets
          8. Exercises
          9. Summary
      13. 5. Bond and Stock Valuation
        1. Introduction to interest rates
        2. Term structure of interest rates
        3. Bond evaluation
        4. Stock valuation
        5. A new data type – dictionary
          1. Appendix A – simple interest rate versus compounding interest rate
          2. Appendix B – several Python functions related to interest conversion
          3. Appendix C – Python program for rateYan.py
          4. Appendix D – Python program to estimate stock price based on an n-period model
          5. Appendix E – Python program to estimate the duration for a bond
          6. Appendix F – data case #2 – fund raised from a new bond issue
        6. Summary
      14. 6. Capital Asset Pricing Model
        1. Introduction to CAPM
        2. Moving beta
        3. Adjusted beta
          1. Scholes and William adjusted beta
        4. Extracting output data
          1. Outputting data to text files
          2. Saving our data to a .csv file
          3. Saving our data to an Excel file
          4. Saving our data to a pickle dataset
          5. Saving our data to a binary file
          6. Reading data from a binary file
        5. Simple string manipulation
        6. Python via Canopy
        7. References
        8. Exercises
        9. Summary
      15. 7. Multifactor Models and Performance Measures
        1. Introduction to the Fama-French three-factor model
        2. Fama-French three-factor model
        3. Fama-French-Carhart four-factor model and Fama-French five-factor model
        4. Implementation of Dimson (1979) adjustment for beta
        5. Performance measures
        6. How to merge different datasets
          1. Appendix A – list of related Python datasets
          2. Appendix B – Python program to generate ffMonthly.pkl
          3. Appendix C – Python program for Sharpe ratio
          4. Appendix D – data case #4 – which model is the best, CAPM, FF3, FFC4, or FF5, or others?
        7. References
        8. Exercises
        9. Summary
      16. 8. Time-Series Analysis
        1. Introduction to time-series analysis
        2. Merging datasets based on a date variable
          1. Using pandas.date_range() to generate one dimensional time-series
          2. Return estimation
          3. Converting daily returns to monthly ones
          4. Merging datasets by date
        3. Understanding the interpolation technique
          1. Merging data with different frequencies
        4. Tests of normality
          1. Estimating fat tails
          2. T-test and F-test
          3. Tests of equal variances
          4. Testing the January effect
        5. 52-week high and low trading strategy
        6. Estimating Roll's spread
        7. Estimating Amihud's illiquidity
        8. Estimating Pastor and Stambaugh (2003) liquidity measure
        9. Fama-MacBeth regression
        10. Durbin-Watson
        11. Python for high-frequency data
        12. Spread estimated based on high-frequency data
        13. Introduction to CRSP
        14. References
          1. Appendix A – Python program to generate GDP dataset usGDPquarterly2.pkl
          2. Appendix B – critical values of F for the 0.05 significance level
          3. Appendix C – data case #4 - which political party manages the economy better?
        15. Exercises
        16. Summary
      17. 9. Portfolio Theory
        1. Introduction to portfolio theory
        2. A 2-stock portfolio
        3. Optimization – minimization
        4. Forming an n-stock portfolio
        5. Constructing an optimal portfolio
        6. Constructing an efficient frontier with n stocks
        7. References
          1. Appendix A – data case #5 - which industry portfolio do you prefer?
          2. Appendix B – data case #6 - replicate S&P500 monthly returns
        8. Exercises
        9. Summary
      18. 10. Options and Futures
        1. Introducing futures
        2. Payoff and profit/loss functions for call and put options
        3. European versus American options
          1. Understanding cash flows, types of options, rights and obligations
        4. Black-Scholes-Merton option model on non-dividend paying stocks
        5. Generating our own module p4f
        6. European options with known dividends
        7. Various trading strategies
          1. Covered-call – long a stock and short a call
          2. Straddle – buy a call and a put with the same exercise prices
          3. Butterfly with calls
          4. The relationship between input values and option values
          5. Greeks
        8. Put-call parity and its graphic presentation
          1. The put-call ratio for a short period with a trend
        9. Binomial tree and its graphic presentation
          1. Binomial tree (CRR) method for European options
          2. Binomial tree (CRR) method for American options
        10. Hedging strategies
        11. Implied volatility
        12. Binary-search
        13. Retrieving option data from Yahoo! Finance
        14. Volatility smile and skewness
        15. References
          1. Appendix A – data case 6: portfolio insurance
        16. Exercises
        17. Summary
      19. 11. Value at Risk
        1. Introduction to VaR
        2. Normality tests
        3. Skewness and kurtosis
        4. Modified VaR
        5. VaR based on sorted historical returns
        6. Simulation and VaR
        7. VaR for portfolios
        8. Backtesting and stress testing
        9. Expected shortfall
          1. Appendix A – data case 7 – VaR estimation for individual stocks and a portfolio
        10. References
        11. Exercises
        12. Summary
      20. 12. Monte Carlo Simulation
        1. Importance of Monte Carlo Simulation
        2. Generating random numbers from a standard normal distribution
          1. Drawing random samples from a normal distribution
        3. Generating random numbers with a seed
          1. Random numbers from a normal distribution
          2. Histogram for a normal distribution
          3. Graphical presentation of a lognormal distribution
        4. Generating random numbers from a uniform distribution
        5. Using simulation to estimate the pi value
        6. Generating random numbers from a Poisson distribution
        7. Selecting m stocks randomly from n given stocks
        8. With/without replacements
        9. Distribution of annual returns
        10. Simulation of stock price movements
        11. Graphical presentation of stock prices at options' maturity dates
        12. Replicating a Black-Scholes-Merton call using simulation
          1. Exotic option #1 – using the Monte Carlo Simulation to price average
          2. Exotic option #2 – pricing barrier options using the Monte Carlo Simulation
        13. Liking two methods for VaR using simulation
        14. Capital budgeting with Monte Carlo Simulation
        15. Python SimPy module
        16. Comparison between two social policies – basic income and basic job
        17. Finding an efficient frontier based on two stocks by using simulation
        18. Constructing an efficient frontier with n stocks
        19. Long-term return forecasting
        20. Efficiency, Quasi-Monte Carlo, and Sobol sequences
          1. Appendix A – data case #8 - Monte Carlo Simulation and blackjack
        21. References
        22. Exercises
        23. Summary
      21. 13. Credit Risk Analysis
        1. Introduction to credit risk analysis
        2. Credit rating
        3. Credit spread
        4. YIELD of AAA-rated bond, Altman Z-score
        5. Using the KMV model to estimate the market value of total assets and its volatility
        6. Term structure of interest rate
        7. Distance to default
        8. Credit default swap
          1. Appendix A – data case #8 - predicting bankruptcy by using Z-score
        9. References
        10. Exercises
        11. Summary
      22. 14. Exotic Options
        1. European, American, and Bermuda options
        2. Chooser options
        3. Shout options
        4. Binary options
        5. Rainbow options
        6. Pricing average options
        7. Pricing barrier options
        8. Barrier in-and-out parity
        9. Graph of up-and-out and up-and-in parity
        10. Pricing lookback options with floating strikes
          1. Appendix A – data case 7 – hedging crude oil
        11. References
        12. Exercises
        13. Summary
      23. 15. Volatility, Implied Volatility, ARCH, and GARCH
        1. Conventional volatility measure – standard deviation
        2. Tests of normality
        3. Estimating fat tails
        4. Lower partial standard deviation and Sortino ratio
        5. Test of equivalency of volatility over two periods
        6. Test of heteroskedasticity, Breusch, and Pagan
        7. Volatility smile and skewness
        8. Graphical presentation of volatility clustering
        9. The ARCH model
        10. Simulating an ARCH (1) process
        11. The GARCH model
        12. Simulating a GARCH process
        13. Simulating a GARCH (p,q) process using modified garchSim()
        14. GJR_GARCH by Glosten, Jagannanthan, and Runkle
        15. References
          1. Appendix A – data case 8 - portfolio hedging using VIX calls
            1. References
          2. Appendix B – data case 8 - volatility smile and its implications
        16. Exercises
        17. Summary
      24. Index

    Product information

    • Title: Python for Finance - Second Edition
    • Author(s): Yuxing Yan
    • Release date: June 2017
    • Publisher(s): Packt Publishing
    • ISBN: 9781787125698