Table of Contents
Chapter 1: Introduction and Installation of Python 9 Introduction to Python 10 Installing Python 12 Different versions of Python 12 Ways to launch Python 13
Launching Python with GUI 13
Launching Python from the Python command line 14
Launching Python from our own DOS window 15 Quitting Python 16 Error messages 16 Python language is case sensitive 17 Initializing the variable 17 Finding the help window 18 Finding manuals and tutorials 19 Finding the version of Python 21 Summary 21 Exercises 22
Chapter 2: Using Python as an Ordinary Calculator 23 Assigning values to variables 24
Displaying the value of a variable 24 Error messages 24
Can't call a variable without assignment 25 Choosing meaningful names 25 Using dir() to find variables and functions 26
Deleting or unsigning a variable 27 Basic math operations – addition, subtraction, multiplication, and division 28 The power function, floor, and remainder 28
A true power function 30 Choosing appropriate precision 31 Finding out more information about a specific built-in function 32
Listing all built-in functions 32 Importing the math module 33
The pi, e, log, and exponential functions 34
"import math" versus "from math import *" 34 A few frequently used functions 36
The print() function 36
The type() function 36
Last expression _ (underscore) 36
Combining two strings 37
The upper() function 37 The tuple data type 39 Summary 40 Exercises 40
Chapter 3: Using Python as a Financial Calculator 43 Writing a Python function without saving it 44 Default input values for a function 45 Indentation is critical in Python 45 Checking the existence of our functions 46 Defining functions from our Python editor 47 Activating our function using the import function 48 Debugging a program from a Python editor 48 Two ways to call our pv_f() function 49 Generating our own module 50 Types of comments 51
The first type of comment 51
The second type of comment 52
Finding information about our pv_f() function 52 The if() function 53 Annuity estimation 54 Converting the interest rates 55 Continuously compounded interest rate 57 A data type – list 58 Net present value and the NPV rule 58 Defining the payback period and the payback period rule 60 Defining IRR and the IRR rule 61 Showing certain files in a specific subdirectory 62 Using Python as a financial calculator 63 Adding our project directory to the path 64 Summary 66 Exercises 67
Chapter 4: 13 Lines of Python to Price a Call Option 71 Writing a program – the empty shell method 73 Writing a program – the comment-all-out method 75 Using and debugging other programs 76 Summary 76 Exercises 77
Chapter 5: Introduction to Modules 79 What is a module? 80 Importing a module 80
Adopting a short name for an imported module 81
Showing all functions in an imported module 82
Comparing "import math" and "from math import *" 82
Deleting an imported module 83
Importing only a few needed functions 84
Finding out all built-in modules 85
Finding out all the available modules 86
Finding the location of an imported module 87
More information about modules 88
Finding a specific uninstalled module 90 Module dependency 90 Summary 92 Exercises 93
Chapter 6: Introduction to NumPy and SciPy 95 Installation of NumPy and SciPy 96 Launching Python from Anaconda 96
Examples of using NumPy 97
Examples of using SciPy 98 Showing all functions in NumPy and SciPy 102 More information about a specific function 103 Understanding the list data type 103 Working with arrays of ones, zeros, and the identity matrix 104 Performing array manipulations 105 Performing array operations with +, -, *, / 105
Performing plus and minus operations 105
Performing a matrix multiplication operation 105
Performing an item-by-item multiplication operation 107 The x.sum() dot function 107 Looping through an array 108 Using the help function related to modules 108 A list of subpackages for SciPy 109 Cumulative standard normal distribution 109 Logic relationships related to an array 110 Statistic submodule (stats) from SciPy 111 Interpolation in SciPy 112 Solving linear equations using SciPy 113 Generating random numbers with a seed 114 Finding a function from an imported module 116 Understanding optimization 116 Linear regression and Capital Assets Pricing Model (CAPM) 117 Retrieving data from an external text file 118
The loadtxt() and getfromtxt() functions 118 Installing NumPy independently 119 Understanding the data types 119 Summary 120 Exercises 120
Chapter 7: Visual Finance via Matplotlib 123 Installing matplotlib via ActivePython 124 Alternative installation via Anaconda 125 Understanding how to use matplotlib 125 Understanding simple and compounded interest rates 129 Adding texts to our graph 131 Working with DuPont identity 133 Understanding the Net Present Value (NPV) profile 135
Using colors effectively 137
Using different shapes 139 Graphical representation of the portfolio diversification effect 140
Number of stocks and portfolio risk 142 Retrieving historical price data from Yahoo! Finance 144
Histogram showing return distribution 145
Comparing stock and market returns 148 Understanding the time value of money 150 Candlesticks representation of IBM's daily price 151
Graphical representation of two-year price movement 153 IBM's intra-day graphical representations 154 Presenting both closing price and trading volume 156
Adding mathematical formulae to our graph 157
Adding simple images to our graphs 158
Saving our figure to a file 159 Performance comparisons among stocks 160 Comparing return versus volatility for several stocks 161 Finding manuals, examples, and videos 163 Installing the matplotlib module independently 163 Summary 163 Exercises 164
Chapter 8: Statistical Analysis of Time Series 167 Installing Pandas and statsmodels 168
Launching Python using the Anaconda command prompt 169
Launching Python using the DOS window 169
Launching Python using Spyder 170 Using Pandas and statsmodels 171
Using Pandas 171
Examples from statsmodels 173 Open data sources 174 Retrieving data to our programs 176
Inputting data from the clipboard 176
Retrieving historical price data from Yahoo! Finance 177
Inputting data from a text file 178
Inputting data from an Excel file 179
Inputting data from a CSV file 180
Retrieving data from a web page 180
Inputting data from a MATLAB dataset 181 Several important functionalities 182
Using pd.Series() to generate one-dimensional time series 182
Using date variables 183
Using the DataFrame 183 Return estimation 185
Converting daily returns to monthly returns 187
Converting daily returns to annual returns 190 Merging datasets by date 191
Forming an n-stock portfolio 192 T-test and F-test 193
Tests of equal means and equal variances 194
Testing the January effect 195 Many useful applications 196
52-week high and low trading strategy 196
Roll's model to estimate spread (1984) 197
Amihud's model for illiquidity (2002) 198
Pastor and Stambaugh (2003) liquidity measure 199
Fama-French three-factor model 204
Fama-MacBeth regression 206
Estimating rolling beta 207
Understanding VaR 210 Constructing an efficient frontier 211
Estimating a variance-covariance matrix 212
Optimization – minimization 214
Constructing an optimal portfolio 215
Constructing an efficient frontier with n stocks 217 Understanding the interpolation technique 220 Outputting data to external files 221
Outputting data to a text file 221
Saving our data to a binary file 222
Reading data from a binary file 222 Python for high-frequency data 222
Spread estimated based on high-frequency data 227 More on using Spyder 228 A useful dataset 230 Summary 232 Exercise 232
Chapter 9: The Black-Scholes-Merton Option Model 237 Payoff and profit/loss functions for the call and put options 238 European versus American options 242 Cash flows, types of options, a right, and an obligation 243 Normal distribution, standard normal distribution, and cumulative standard normal distribution 243 The Black-Scholes-Merton option model on non-dividend paying stocks 247 The p4f module for options 248 European options with known dividends 250 Various trading strategies 251
Covered call – long a stock and short a call 252
Straddle – buy a call and a put with the same exercise prices 253
A calendar spread 254
Butterfly with calls 256 Relationship between input values and option values 257 Greek letters for options 258 The put-call parity and its graphical representation 259 Binomial tree (the CRR method) and its graphical representation 261
The binomial tree method for European options 268
The binomial tree method for American options 268 Hedging strategies 269 Summary 270 Exercises 271
Chapter 10: Python Loops and Implied Volatility 275 Definition of an implied volatility 276 Understanding a for loop 277
Estimating the implied volatility by using a for loop 278
Implied volatility function based on a European call 279
Implied volatility based on a put option model 280
The enumerate() function 281 Estimation of IRR via a for loop 282
Estimation of multiple IRRs 283 Understanding a while loop 284 Using keyboard commands to stop an infinitive loop 285
Estimating implied volatility by using a while loop 286
Nested (multiple) for loops 288 Estimating implied volatility by using an American call 288 Measuring efficiency by time spent in finishing a program 289 The mechanism of a binary search 290 Sequential versus random access 292 Looping through an array/DataFrame 293
Assignment through a for loop 294
Looping through a dictionary 294 Retrieving option data from CBOE 295 Retrieving option data from Yahoo! Finance 297
Different expiring dates from Yahoo! Finance 299
Retrieving the current price from Yahoo! Finance 300 The put-call ratio 300
The put-call ratio for a short period with a trend 302 Summary 303 Exercises 304
Chapter 11: Monte Carlo Simulation and Options 307 Generating random numbers from a standard normal distribution 308
Drawing random samples from a normal (Gaussian) distribution 309
Generating random numbers with a seed 309
Generating n random numbers from a normal distribution 310
Histogram for a normal distribution 310
Graphical presentation of a lognormal distribution 311 Generating random numbers from a uniform distribution 312 Using simulation to estimate the pi value 313 Generating random numbers from a Poisson distribution 315
Selecting m stocks randomly from n given stocks 315 Bootstrapping with/without replacements 317 Distribution of annual returns 319 Simulation of stock price movements 320
Graphical presentation of stock prices at options' maturity dates 322 Finding an efficient portfolio and frontier 324
Finding an efficient frontier based on two stocks 324
Impact of different correlations 326
Constructing an efficient frontier with n stocks 329 Geometric versus arithmetic mean 332 Long-term return forecasting 333 Pricing a call using simulation 334 Exotic options 335
Using the Monte Carlo simulation to price average options 335
Pricing barrier options using the Monte Carlo simulation 337 Barrier in-and-out parity 339
Graphical presentation of an up-and-out and up-and-in parity 340 Pricing lookback options with floating strikes 342 Using the Sobol sequence to improve the efficiency 344 Summary 344 Exercises 345
Chapter 12: Volatility Measures and GARCH 347 Conventional volatility measure – standard deviation 348 Tests of normality 349
Estimating fat tails 350 Lower partial standard deviation 352 Test of equivalency of volatility over two periods 354 Test of heteroskedasticity, Breusch, and Pagan (1979) 355 Retrieving option data from Yahoo! Finance 358 Volatility smile and skewness 360
Graphical presentation of volatility clustering 362