You are previewing Python for Finance.
O'Reilly logo
Python for Finance

Book Description

If your interest is finance and trading, then using Python to build a financial calculator makes absolute sense. As does this book which is a hands-on guide covering everything from option theory to time series.

In Detail

Python is a free and powerful tool that can be used to build a financial calculator and price options, and can also explain many trading strategies and test various hypotheses. This book details the steps needed to retrieve time series data from different public data sources.

Python for Finance explores the basics of programming in Python. It is a step-by-step tutorial that will teach you, with the help of concise, practical programs, how to run various statistic tests. This book introduces you to the basic concepts and operations related to Python. You will also learn how to estimate illiquidity, Amihud (2002), liquidity measure, Pastor and Stambaugh (2003), Roll spread (1984), spread based on high-frequency data, beta (rolling beta), draw volatility smile and skewness, and construct a binomial tree to price American options.

This book is a hands-on guide with easy-to-follow examples to help you learn about option theory, quantitative finance, financial modeling, and time series using Python.

What You Will Learn

  • Build a financial calculator based on Python
  • Learn how to price various types of options such as European, American, average, lookback, and barrier options
  • Write Python programs to download data from Yahoo! Finance
  • Estimate returns and convert daily returns into monthly or annual returns
  • Form an n-stock portfolio and estimate its variance-covariance matrix
  • Estimate VaR (Value at Risk) for a stock or portfolio
  • Run CAPM (Capital Asset Pricing Model) and the Fama-French 3-factor model
  • Learn how to optimize a portfolio and draw an efficient frontier
  • Conduct various statistic tests such as T-tests, F-tests, and normality tests
  • Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

    Table of Contents

    1. Python for Finance
      1. Table of Contents
      2. Python for Finance
      3. Credits
      4. About the Author
      5. Acknowledgments
      6. About the Reviewers
        1. Support files, eBooks, discount offers and more
          1. Why subscribe?
          2. Free access for Packt account holders
      8. Preface
        1. Why Python?
        2. A programming book written by a finance professor
        3. Small programs oriented
        4. Using real-world data
        5. What this book covers
        6. What could you achieve after reading this book?
        7. Who this book is for
        8. Conventions
        9. Two ways to use the book
        10. Reader feedback
        11. Customer support
          1. Downloading the example code
          2. Downloading the color images of this book
          3. Errata
          4. Piracy
          5. Questions
      9. 1. Introduction and Installation of Python
        1. Introduction to Python
        2. Installing Python
        3. Different versions of Python
        4. Ways to launch Python
          1. Launching Python with GUI
          2. Launching Python from the Python command line
          3. Launching Python from our own DOS window
        5. Quitting Python
        6. Error messages
        7. Python language is case sensitive
        8. Initializing the variable
        9. Finding the help window
        10. Finding manuals and tutorials
        11. Finding the version of Python
        12. Summary
        13. Exercises
      10. 2. Using Python as an Ordinary Calculator
        1. Assigning values to variables
          1. Displaying the value of a variable
        2. Error messages
          1. Can't call a variable without assignment
        3. Choosing meaningful names
        4. Using dir() to find variables and functions
          1. Deleting or unsigning a variable
        5. Basic math operations – addition, subtraction, multiplication, and division
        6. The power function, floor, and remainder
          1. A true power function
        7. Choosing appropriate precision
        8. Finding out more information about a specific built-in function
          1. Listing all built-in functions
        9. Importing the math module
          1. The pi, e, log, and exponential functions
          2. "import math" versus "from math import *"
        10. A few frequently used functions
          1. The print() function
          2. The type() function
          3. Last expression _ (underscore)
          4. Combining two strings
          5. The upper() function
        11. The tuple data type
        12. Summary
        13. Exercises
      11. 3. Using Python as a Financial Calculator
        1. Writing a Python function without saving it
        2. Default input values for a function
        3. Indentation is critical in Python
        4. Checking the existence of our functions
        5. Defining functions from our Python editor
        6. Activating our function using the import function
        7. Debugging a program from a Python editor
        8. Two ways to call our pv_f() function
        9. Generating our own module
        10. Types of comments
          1. The first type of comment
          2. The second type of comment
            1. Finding information about our pv_f() function
        11. The if() function
        12. Annuity estimation
        13. Converting the interest rates
        14. Continuously compounded interest rate
        15. A data type – list
        16. Net present value and the NPV rule
        17. Defining the payback period and the payback period rule
        18. Defining IRR and the IRR rule
        19. Showing certain files in a specific subdirectory
        20. Using Python as a financial calculator
        21. Adding our project directory to the path
        22. Summary
        23. Exercises
      12. 4. 13 Lines of Python to Price a Call Option
        1. Writing a program – the empty shell method
        2. Writing a program – the comment-all-out method
        3. Using and debugging other programs
        4. Summary
        5. Exercises
      13. 5. Introduction to Modules
        1. What is a module?
        2. Importing a module
          1. Adopting a short name for an imported module
          2. Showing all functions in an imported module
          3. Comparing "import math" and "from math import *"
          4. Deleting an imported module
          5. Importing only a few needed functions
          6. Finding out all built-in modules
          7. Finding out all the available modules
          8. Finding the location of an imported module
          9. More information about modules
          10. Finding a specific uninstalled module
        3. Module dependency
        4. Summary
        5. Exercises
      14. 6. Introduction to NumPy and SciPy
        1. Installation of NumPy and SciPy
        2. Launching Python from Anaconda
          1. Examples of using NumPy
          2. Examples of using SciPy
        3. Showing all functions in NumPy and SciPy
        4. More information about a specific function
        5. Understanding the list data type
        6. Working with arrays of ones, zeros, and the identity matrix
        7. Performing array manipulations
        8. Performing array operations with +, -, *, /
          1. Performing plus and minus operations
          2. Performing a matrix multiplication operation
          3. Performing an item-by-item multiplication operation
        9. The x.sum() dot function
        10. Looping through an array
        11. Using the help function related to modules
        12. A list of subpackages for SciPy
        13. Cumulative standard normal distribution
        14. Logic relationships related to an array
        15. Statistic submodule (stats) from SciPy
        16. Interpolation in SciPy
        17. Solving linear equations using SciPy
        18. Generating random numbers with a seed
        19. Finding a function from an imported module
        20. Understanding optimization
        21. Linear regression and Capital Assets Pricing Model (CAPM)
        22. Retrieving data from an external text file
          1. The loadtxt() and getfromtxt() functions
        23. Installing NumPy independently
        24. Understanding the data types
        25. Summary
        26. Exercises
      15. 7. Visual Finance via Matplotlib
        1. Installing matplotlib via ActivePython
        2. Alternative installation via Anaconda
        3. Understanding how to use matplotlib
        4. Understanding simple and compounded interest rates
        5. Adding texts to our graph
        6. Working with DuPont identity
        7. Understanding the Net Present Value (NPV) profile
          1. Using colors effectively
          2. Using different shapes
        8. Graphical representation of the portfolio diversification effect
          1. Number of stocks and portfolio risk
        9. Retrieving historical price data from Yahoo! Finance
          1. Histogram showing return distribution
          2. Comparing stock and market returns
        10. Understanding the time value of money
        11. Candlesticks representation of IBM's daily price
          1. Graphical representation of two-year price movement
        12. IBM's intra-day graphical representations
        13. Presenting both closing price and trading volume
          1. Adding mathematical formulae to our graph
          2. Adding simple images to our graphs
          3. Saving our figure to a file
        14. Performance comparisons among stocks
        15. Comparing return versus volatility for several stocks
        16. Finding manuals, examples, and videos
        17. Installing the matplotlib module independently
        18. Summary
        19. Exercises
      16. 8. Statistical Analysis of Time Series
        1. Installing Pandas and statsmodels
          1. Launching Python using the Anaconda command prompt
          2. Launching Python using the DOS window
          3. Launching Python using Spyder
        2. Using Pandas and statsmodels
          1. Using Pandas
          2. Examples from statsmodels
        3. Open data sources
        4. Retrieving data to our programs
          1. Inputting data from the clipboard
          2. Retrieving historical price data from Yahoo! Finance
          3. Inputting data from a text file
          4. Inputting data from an Excel file
          5. Inputting data from a CSV file
          6. Retrieving data from a web page
          7. Inputting data from a MATLAB dataset
        5. Several important functionalities
          1. Using pd.Series() to generate one-dimensional time series
          2. Using date variables
          3. Using the DataFrame
        6. Return estimation
          1. Converting daily returns to monthly returns
          2. Converting daily returns to annual returns
        7. Merging datasets by date
          1. Forming an n-stock portfolio
        8. T-test and F-test
          1. Tests of equal means and equal variances
          2. Testing the January effect
        9. Many useful applications
          1. 52-week high and low trading strategy
          2. Roll's model to estimate spread (1984)
          3. Amihud's model for illiquidity (2002)
          4. Pastor and Stambaugh (2003) liquidity measure
          5. Fama-French three-factor model
          6. Fama-MacBeth regression
          7. Estimating rolling beta
          8. Understanding VaR
        10. Constructing an efficient frontier
          1. Estimating a variance-covariance matrix
          2. Optimization – minimization
          3. Constructing an optimal portfolio
          4. Constructing an efficient frontier with n stocks
        11. Understanding the interpolation technique
        12. Outputting data to external files
          1. Outputting data to a text file
          2. Saving our data to a binary file
          3. Reading data from a binary file
        13. Python for high-frequency data
          1. Spread estimated based on high-frequency data
        14. More on using Spyder
        15. A useful dataset
        16. Summary
        17. Exercise
      17. 9. The Black-Scholes-Merton Option Model
        1. Payoff and profit/loss functions for the call and put options
        2. European versus American options
        3. Cash flows, types of options, a right, and an obligation
        4. Normal distribution, standard normal distribution, and cumulative standard normal distribution
        5. The Black-Scholes-Merton option model on non-dividend paying stocks
        6. The p4f module for options
        7. European options with known dividends
        8. 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. A calendar spread
          4. Butterfly with calls
        9. Relationship between input values and option values
        10. Greek letters for options
        11. The put-call parity and its graphical representation
        12. Binomial tree (the CRR method) and its graphical representation
          1. The binomial tree method for European options
          2. The binomial tree method for American options
        13. Hedging strategies
        14. Summary
        15. Exercises
      18. 10. Python Loops and Implied Volatility
        1. Definition of an implied volatility
        2. Understanding a for loop
          1. Estimating the implied volatility by using a for loop
          2. Implied volatility function based on a European call
          3. Implied volatility based on a put option model
          4. The enumerate() function
        3. Estimation of IRR via a for loop
          1. Estimation of multiple IRRs
        4. Understanding a while loop
        5. Using keyboard commands to stop an infinitive loop
          1. Estimating implied volatility by using a while loop
          2. Nested (multiple) for loops
        6. Estimating implied volatility by using an American call
        7. Measuring efficiency by time spent in finishing a program
        8. The mechanism of a binary search
        9. Sequential versus random access
        10. Looping through an array/DataFrame
          1. Assignment through a for loop
          2. Looping through a dictionary
        11. Retrieving option data from CBOE
        12. Retrieving option data from Yahoo! Finance
          1. Different expiring dates from Yahoo! Finance
          2. Retrieving the current price from Yahoo! Finance
        13. The put-call ratio
          1. The put-call ratio for a short period with a trend
        14. Summary
        15. Exercises
      19. 11. Monte Carlo Simulation and Options
        1. Generating random numbers from a standard normal distribution
          1. Drawing random samples from a normal (Gaussian) distribution
          2. Generating random numbers with a seed
          3. Generating n random numbers from a normal distribution
            1. Histogram for a normal distribution
          4. Graphical presentation of a lognormal distribution
        2. Generating random numbers from a uniform distribution
        3. Using simulation to estimate the pi value
        4. Generating random numbers from a Poisson distribution
          1. Selecting m stocks randomly from n given stocks
        5. Bootstrapping with/without replacements
        6. Distribution of annual returns
        7. Simulation of stock price movements
          1. Graphical presentation of stock prices at options' maturity dates
        8. Finding an efficient portfolio and frontier
          1. Finding an efficient frontier based on two stocks
            1. Impact of different correlations
          2. Constructing an efficient frontier with n stocks
        9. Geometric versus arithmetic mean
        10. Long-term return forecasting
        11. Pricing a call using simulation
        12. Exotic options
          1. Using the Monte Carlo simulation to price average options
          2. Pricing barrier options using the Monte Carlo simulation
        13. Barrier in-and-out parity
          1. Graphical presentation of an up-and-out and up-and-in parity
        14. Pricing lookback options with floating strikes
        15. Using the Sobol sequence to improve the efficiency
        16. Summary
        17. Exercises
      20. 12. Volatility Measures and GARCH
        1. Conventional volatility measure – standard deviation
        2. Tests of normality
          1. Estimating fat tails
        3. Lower partial standard deviation
        4. Test of equivalency of volatility over two periods
        5. Test of heteroskedasticity, Breusch, and Pagan (1979)
        6. Retrieving option data from Yahoo! Finance
        7. Volatility smile and skewness
          1. Graphical presentation of volatility clustering
        8. The ARCH model
          1. Simulating an ARCH (1) process
        9. The GARCH (Generalized ARCH) model
          1. Simulating a GARCH process
          2. Simulating a GARCH (p,q) process using modified garchSim()
          3. GJR_GARCH by Glosten, Jagannanthan, and Runkle (1993)
        10. Summary
        11. Exercises
      21. Index