Python for Finance


Python for Finance
eBook: $26.99
Formats: PDF, PacktLib, ePub and Mobi formats
$22.94
save 15%!
Print + free eBook + free PacktLib access to the book: $71.98    Print cover: $44.99
$44.99
save 37%!
Free Shipping!
UK, US, Europe and selected countries in Asia.
Also available on:
Overview
Table of Contents
Author
Support
Sample Chapters
  • 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

Book Details

Language : English
Paperback : 408 pages [ 235mm x 191mm ]
Release Date : April 2014
ISBN : 1783284374
ISBN 13 : 9781783284375
Author(s) : Yuxing Yan
Topics and Technologies : All Books, Big Data and Business Intelligence, Open Source


Table of Contents

Preface
Chapter 1: Introduction and Installation of Python
Chapter 2: Using Python as an Ordinary Calculator
Chapter 3: Using Python as a Financial Calculator
Chapter 4: 13 Lines of Python to Price a Call Option
Chapter 5: Introduction to Modules
Chapter 6: Introduction to NumPy and SciPy
Chapter 7: Visual Finance via Matplotlib
Chapter 8: Statistical Analysis of Time Series
Chapter 9: The Black-Scholes-Merton Option Model
Chapter 10: Python Loops and Implied Volatility
Chapter 11: Monte Carlo Simulation and Options
Chapter 12: Volatility Measures and GARCH
Index
  • 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 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

Yuxing Yan

Yuxing Yan graduated from McGill university with a PhD in finance. He has taught various finance courses, such as Financial Modeling, Options and Futures, Portfolio Theory, Quantitative Financial Analysis, Corporate Finance, and Introduction to Financial Databases to undergraduate and graduate students at seven universities: two in Canada, one in Singapore, and four in the USA.

Dr. Yan has actively done research with several publications in Journal of Accounting and Finance, Journal of Banking and Finance, Journal of Empirical Finance, Real Estate Review, Pacific Basin Finance Journal, Applied Financial Economics, and Annals of Operations Research. For example, his latest publication, co-authored with Shaojun Zhang, will appear in the Journal of Banking and Finance in 2014. His research areas include investment, market microstructure, and open source finance.

He is proficient at several computer languages such as SAS, R, MATLAB, C, and Python. From 2003 to 2010, he worked as a technical director at Wharton Research Data Services (WRDS), where he debugged several hundred computer programs related to research for WRDS users. After that, he returned to teaching in 2010 and introduced R into several quantitative courses at two universities. Based on lecture notes, he has the first draft of an unpublished manuscript titled Financial Modeling using R.

In addition, he is an expert on financial data. While teaching at NTU in Singapore, he offered a course called Introduction to Financial Databases to doctoral students. While working at WRDS, he answered numerous questions related to financial databases and helped update CRSP, Compustat, IBES, and TAQ (NYSE high-frequency database). In 2007, Dr. Yan and S.W. Zhu (his co-author) published a book titled Financial Databases, Shiwu Zhu and Yuxing Yan, Tsinghua University Press. Currently, he spends considerable time and effort on public financial data. If you have any queries, you can always contact him at yany@canisius.edu.

Sorry, we don't have any reviews for this title yet.

Code Downloads

Download the code and support files for this book.


Submit Errata

Please let us know if you have found any errors not listed on this list by completing our errata submission form. Our editors will check them and add them to this list. Thank you.


Errata

- 22 submitted: last submission 15 Jul 2014

Page Number: 44  Type of errata: Code related   Chapter Number: 3

 

It is :>>>def pv_f(pv,r,n):

 

It should be: >>>def pv_f(fv,r,n):

Page Number: 48  Type of errata: Technical  Chapter Number: 3

 

It is: Since  test01 could be treated the same way as the  math module discussed in  Chapter
2,  Using Python as an Ordinary Calculator, we have to use  test01.pv() instead of
pv_f()

 

It should be: Since  test01 could be treated the same way as the  math module discussed in  Chapter
2,  Using Python as an Ordinary Calculator, we have to use  test01.pv_f() instead of
pv_f()

Page Number: 58  Type of errata: Technical  Chapter Number: 3

 

It is : A list? is another type of data. Unlike a tuple, which uses parentheses, lists use
square brackets, [ and ], as shown in the following code. A list could include
different types of data, such  as string, integer, fl oat, and A list itself:


It should be: A list is another type of data. Unlike a tuple, which uses parentheses, lists use
square brackets, [ and ], as shown in the following code. A list could include
different types of data, such  as string, integer, fl oat, and a list itself:

Page Number: 110 Type of Errata: Code related  Chapter Number: 6

 

It is : >>>price=bs_call(40,40,1,0.03,0.2)

 

It should be: >>>price=bs_call(40,1,0.03,0.2)

Page Number: 104 Type of errata: Code related Chapter Number :6

 

It is: >>>i=np.ones_linke(g)

 

It should be: >>>i=np.ones_like(g)

Page Number: 108 Type of errata: Code related  Chapter Number: 108

 

It is: >>>import numpy as np
>>>cash_flows=np.array([-100,50,40,30,25,-10,50,100])
>>>for cash in cash_flows:
        print x

 

It should be: >>>import numpy as np
>>>cash_flows=np.array([-100,50,40,30,25,-10,50,100])
>>>for cash in cash_flows:
        print cash

Page Number: 98 Type of errata: Code related Chapter Number :6

 

It is: >>>x=[1,2,3,20]
>>>y=np.array(x1,dtype=float)
>>>y
array([  1.,   2.,   3.,  20.])

It should be: >>>x=[1,2,3,20]
>>>y=np.array(x,dtype=float)
>>>y
array([  1.,   2.,   3.,  20.])

Page Number: 104 Type of errata: Code related Chapter Number :6

 

It is: >>>e2=np.eys(4) # same as above
>>>e3=np.eys(4,k=1) # 1 start from k

It should be: >>>e2=np.eye(4) # same as above
>>>e3=np.eye(4,k=1) # 1 start from k

Page Number: 110 Type of errata: Code related Chapter Number :6

 

It is: defbs_call(S,X,T,r,sigma):
d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))
d2 = d1-sigma*sqrt(T)
return S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2)

It should be: def bs_call(S,X,T,r,sigma):
d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))
d2 = d1-sigma*sqrt(T)
return S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2)

Page Number: 137  Type of errata: Code related   Chapter Number: 7

 

It is: import matplotlib.pyplot as plt
A_EPS = (5.02, 4.54,4.18, 3.73)
B_EPS = (1.35, 1.88, 1.35, 0.73)

 

It should be :

import matplotlib.pyplot as plt

import numpy as np
A_EPS = (5.02, 4.54,4.18, 3.73)
B_EPS = (1.35, 1.88, 1.35, 0.73)

Page Number: 134 Type of errata: Code related Chapter Number: 7

 

It is : p3 = plt.bar(ind, c, width, color='y', bottom=[a[j] +b[j] for j in plt.
xticks(ind+width/2., ('IBM', 'DELL', 'WMT') )

 

It should be:

p3 = plt.bar(ind, c, width, color='y', bottom=[a[j] +b[j] for j in range(len(a))])

plt.xticks(ind+width/2., ('IBM', 'DELL', 'WMT') )

Page Number: 153  Type of errata: Code related Chapter Number: 7

 

It is: from matplotlib.finance import quotes_historical_yahoo
from matplotlib.dates import MonthLocator,DateFormatter

 

 

 

It should be: from matplotlib.finance import quotes_historical_yahoo
from matplotlib.dates import MonthLocator,DateFormatter

from matplotlib.dates import WeekdayLocator, MONDAY

Also, add the following line:

mondays = WeekdayLocator(MONDAY)

 

At the end of the code add:

plt.show()

 

 

 

Page Number: 160 Type of errata: Code related Chapter Number: 7

 

It is : logret = log(x.aclose[1:]/x.aclose[:-1])

 

It should be:
logret = np.log(x.aclose[1:]/x.aclose[:-1])

It is:


return(exp(sum(logret))-1)

 

It should be:


return(np.exp(sum(logret))-1)

Page Number: 183 Type of errata: Code related Chapter Number: 8

 

It is: >>>import pandas as pd

It should be: >>>import pandas as pd

import numpy as np

 

It is: >>>df=pd.DataFrame(randn(8, 1), columns = ['A'], dtype = 'float32')

 

It should be:
>>>df=pd.DataFrame(np.random.randn(8, 1), columns = ['A'], dtype = 'float32')

 

Page Number: 154 Type of errata:  Code related Chapter Number: 7

 

It is: for i in arange(0,len(p)):

 

It should be: for i in np.arange(0,len(p)):

 

It is: title('Intraday price pattern for ttt'.replace('ttt',ticker))
xlabel('Price of stock')
ylabel('Intro-day price pattern')
plot(x,y)
show()

 

It should be: import matplotlib.pyplot as plt

title('Intraday price pattern for ttt'.replace('ttt',ticker))
xlabel('Price of stock')
ylabel('Intro-day price pattern')
plot(x,y)
show()

Page Number: 171  Type of errata: Code related  Chapter Number: 8

 

It is:

x=10
Print x


It should be:

 

x=10
print x

Page Number: 193  Type of errata: Code related  Chapter Number: 8

 

It is:

 

>>>from scipy import stats
>>>np.random.seed(1235)

 

It should be:

>>>from scipy import stats

>>>import numpy as np
>>>np.random.seed(1235)

Page Number: 238 Type of errata: Code related  Chapter Number: 9

 

It is:

>>>payoff_call(s,x)

 

It should be:


>>>payoff_call(sT,x)

Page Number: 221  Type of errata: Code related Chapter Number: 8

 

It is: >>>x2= re.sub('[\(\)\{\}\.<>a-zA-Z]','', x)

It should be: >>>x2= re.sub('[\(\)\{\}\.<>a-zA-Z]','', p)

Page Number: 71/72  Type of errata: Code related Chapter Number: 4

 

It is:   L*L2   It should be:   L*L/2

 

It isa1*K   It should be:  (a1*K

 

It is:   if X<:  It should be:  if X<0:

Errata type | Code related        Page | 31           Chapter | 2

 

Error: >>>payment2 = round( y, 5)

The variable, 'y' is not declared.


It should read as follows: >>>payment2 = round(payment1, 5)

Errata typr: Code related | Page No: 75

In Step 3:

It is: d1 = (lo(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))

It should be: d1 = (log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))

 

In Step 7:

It is: d1 = d1 = (lo(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))

It should be: d1 = (log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))

Sample chapters

You can view our sample chapters and prefaces of this title on PacktLib or download sample chapters in PDF format.

Frequently bought together

Python for Finance +    Practical Data Analysis =
50% Off
the second eBook
Price for both: $39.00

Buy both these recommended eBooks together and get 50% off the cheapest eBook.

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

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.

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.

Who this book is for

Python for Finance is perfect for graduate students, practitioners, and application developers who wish to learn how to utilize Python to handle their financial needs. Basic programming knowledge is helpful, but not necessary.

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software