Python for Finance

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Build real-life Python applications for quantitative finance and financial engineering with this book and ebook Overview Estimate market risk, form various portfolios, and estimate their variance-covariance matrixes using real-world data Explains many financial concepts and trading strategies with the help of graphs A step-by-step tutorial with many Python programs that will help you learn how to apply Python to finance 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 from this book 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 Approach 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.

Author(s): Yuxing Yan
Edition: 1
Publisher: Packt Publishing
Year: 2014

Language: English
Pages: 321

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