Chapter 1: Python Basics 1 Python installation 1
Installation of Python via Anaconda 2
Launching Python via Spyder 3
Direct installation of Python 4 Variable assignment, empty space, and writing our own programs 7 Writing a Python function 9 Python loops 10
Python loops, if...else conditions 11 Data input 15 Data manipulation 19 Data output 25 Exercises 27 Summary 29Chapter 2: Introduction to Python Modules 31 What is a Python module? 32 Introduction to NumPy 38 Introduction to SciPy 41 Introduction to matplotlib 45
How to install matplotlib 45
Several graphical presentations using matplotlib 45 Introduction to statsmodels 49 Introduction to pandas 51 Python modules related to finance 59 Introduction to the pandas_reader module 60 Two financial calculators 61 How to install a Python module 64
Module dependency 67 Exercises 68 Summary 69
Chapter 3: Time Value of Money 71 Introduction to time value of money 72 Writing a financial calculator in Python 81 Definition of NPV and NPV rule 86 Definition of IRR and IRR rule 88 Definition of payback period and payback period rule 90 Writing your own financial calculator in Python 91 Two general formulae for many functions 92
Appendix A – Installation of Python, NumPy, and SciPy 96
Appendix B – visual presentation of time value of money 98
Appendix C – Derivation of present value of annuity from present value
of one future cash flow and present value of perpetuity 99
Appendix D – How to download a free financial calculator written
in Python 101
Appendix E – The graphical presentation of the relationship between
NPV and R 102
Appendix F – graphical presentation of NPV profile with two IRRs 104
Appendix G – Writing your own financial calculator in Python 105 Exercises 106 Summary 108 Chapter 4: Sources of Data 109 Diving into deeper concepts 110 Retrieving data from Yahoo!Finance 113 Retrieving data from Google Finance 125 Retrieving data from FRED 126 Retrieving data from Prof. French's data library 127 Retrieving data from the Census Bureau, Treasury, and BLS 128 Generating two dozen datasets 130 Several datasets related to CRSP and Compustat 132
Appendix A – Python program for return distribution versus a
normal distribution 137
Appendix B – Python program to a draw
candle-stick picture 138
Appendix C – Python program for price movement 140
Appendix D – Python program to show a picture of a stock's
intra-day movement 141
Appendix E –properties for a pandas DataFrame 142
Appendix F –how to generate a Python dataset with an extension of
.pkl or .pickle 144
Appendix G – data case #1 -generating several Python datasets 145 Exercises 145 Summary 147 Chapter 5: Bond and Stock Valuation 149 Introduction to interest rates 149 Term structure of interest rates 159 Bond evaluation 166 Stock valuation 171 A new data type – dictionary 176
Appendix A – simple interest rate versus compounding interest rate 176
Appendix B – several Python functions related to interest conversion 178
Appendix C – Python program for rateYan.py 179
Appendix D – Python program to estimate stock price based on an
n-period model 180
Appendix E – Python program to estimate the duration for a bond 181
Appendix F – data case #2 – fund raised from a new bond issue 182 Summary 184 Chapter 6: Capital Asset Pricing Model 185 Introduction to CAPM 186 Moving beta 192 Adjusted beta 193
Scholes and William adjusted beta 194 Extracting output data 197
Outputting data to text files 198
Saving our data to a .csv file 198
Saving our data to an Excel file 199
Saving our data to a pickle dataset 199
Saving our data to a binary file 200
Reading data from a binary file 200 Simple string manipulation 201 Python via Canopy 204 References 207 Exercises 209 Summary 212 Chapter 7: Multifactor Models and Performance Measures 213 Introduction to the Fama-French three-factor model 214 Fama-French three-factor model 218
Fama-French-Carhart four-factor model and Fama-French five-factor model 221 Implementation of Dimson (1979) adjustment for beta 223 Performance measures 225 How to merge different datasets 228
Appendix A – list of related Python datasets 235
Appendix B – Python program to generate ffMonthly.pkl 236
Appendix C – Python program for Sharpe ratio 237
Appendix D – data case #4 – which model is the best, CAPM, FF3,
FFC4, or FF5, or others? 238 References 239 Exercises 240 Summary 242 Chapter 8: Time-Series Analysis 243 Introduction to time-series analysis 244 Merging datasets based on a date variable 246
Using pandas.date_range() to generate one dimensional time-series 246
Return estimation 250
Converting daily returns to monthly ones 252
Merging datasets by date 253 Understanding the interpolation technique 254
Merging data with different frequencies 256 Tests of normality 258
Estimating fat tails 260
T-test and F-test 262
Tests of equal variances 263
Testing the January effect 264 52-week high and low trading strategy 265 Estimating Roll's spread 266 Estimating Amihud's illiquidity 267 Estimating Pastor and Stambaugh (2003) liquidity measure 268 Fama-MacBeth regression 269 Durbin-Watson 270 Python for high-frequency data 273 Spread estimated based on high-frequency data 277 Introduction to CRSP 279 References 280
Appendix A – Python program to generate GDP dataset
usGDPquarterly2.pkl 281
Appendix B – critical values of F for the 0.05 significance level 282
Appendix C – data case #4 - which political party manages the
economy better? 283 Exercises 285 Summary 288 Chapter 9: Portfolio Theory 289 Introduction to portfolio theory 290 A 2-stock portfolio 290 Optimization – minimization 294 Forming an n-stock portfolio 301 Constructing an optimal portfolio 307 Constructing an efficient frontier with n stocks 310 References 322
Appendix A – data case #5 - which industry portfolio do you prefer? 322
Appendix B – data case #6 - replicate S&P500 monthly returns 323 Exercises 325 Summary 331 Chapter 10: Options and Futures 333 Introducing futures 334 Payoff and profit/loss functions for call and put options 341 European versus American options 346
Understanding cash flows, types of options, rights and obligations 346 Black-Scholes-Merton option model on non-dividend paying stocks 347 Generating our own module p4f 348 European options with known dividends 349 Various trading strategies 350
Covered-call – long a stock and short a call 351
Straddle – buy a call and a put with the same exercise prices 352
Butterfly with calls 353
The relationship between input values and option values 355
Greeks 356 Put-call parity and its graphic presentation 359
The put-call ratio for a short period with a trend 363 Binomial tree and its graphic presentation 364
Binomial tree (CRR) method for European options 371
Binomial tree (CRR) method for American options 372 Hedging strategies 373 Implied volatility 374 Binary-search 377 Retrieving option data from Yahoo! Finance 378 Volatility smile and skewness 379
References 381
Appendix A – data case 6: portfolio insurance 382 Exercises 384 Summary 387 Chapter 11: Value at Risk 389 Introduction to VaR 390 Normality tests 400 Skewness and kurtosis 402 Modified VaR 403 VaR based on sorted historical returns 405 Simulation and VaR 408 VaR for portfolios 409 Backtesting and stress testing 411 Expected shortfall 413
Appendix A – data case 7 – VaR estimation for individual stocks
and a portfolio 415 References 418 Exercises 418 Summary 420 Chapter 12: Monte Carlo Simulation 421 Importance of Monte Carlo Simulation 422 Generating random numbers from a standard normal distribution 422
Drawing random samples from a normal distribution 423 Generating random numbers with a seed 424
Random numbers from a normal distribution 425
Histogram for a normal distribution 425
Graphical presentation of a lognormal distribution 426 Generating random numbers from a uniform distribution 428 Using simulation to estimate the pi value 429 Generating random numbers from a Poisson distribution 431 Selecting m stocks randomly from n given stocks 432 With/without replacements 433 Distribution of annual returns 435 Simulation of stock price movements 437 Graphical presentation of stock prices at options' maturity dates 439 Replicating a Black-Scholes-Merton call using simulation 441
Exotic option #1 – using the Monte Carlo Simulation to price average 442
Exotic option #2 – pricing barrier options using the Monte Carlo
Simulation 443 Liking two methods for VaR using simulation 445
Capital budgeting with Monte Carlo Simulation 446 Python SimPy module 449 Comparison between two social policies – basic income and basic job 450 Finding an efficient frontier based on two stocks by using simulation 454 Constructing an efficient frontier with n stocks 457 Long-term return forecasting 460 Efficiency, Quasi-Monte Carlo, and Sobol sequences 462
Appendix A – data case #8 - Monte Carlo Simulation and blackjack 463 References 464 Exercises 464 Summary 466 Chapter 13: Credit Risk Analysis 467 Introduction to credit risk analysis 468 Credit rating 468 Credit spread 475 YIELD of AAA-rated bond, Altman Z-score 477 Using the KMV model to estimate the market value of total assets and its volatility 479 Term structure of interest rate 482 Distance to default 485 Credit default swap 486
Appendix A – data case #8 - predicting bankruptcy by using Z-score 487 References 488 Exercises 488 Summary 490 Chapter 14: Exotic Options 491 European, American, and Bermuda options 492 Chooser options 494 Shout options 496 Binary options 497 Rainbow options 498 Pricing average options 505 Pricing barrier options 507 Barrier in-and-out parity 509 Graph of up-and-out and up-and-in parity 510 Pricing lookback options with floating strikes 512
Appendix A – data case 7 – hedging crude oil 514 References 516 Exercises 516 Summary 519
Chapter 15: Volatility, Implied Volatility, ARCH, and GARCH 521 Conventional volatility measure – standard deviation 522 Tests of normality 522 Estimating fat tails 524 Lower partial standard deviation and Sortino ratio 526 Test of equivalency of volatility over two periods 528 Test of heteroskedasticity, Breusch, and Pagan 529 Volatility smile and skewness 532 Graphical presentation of volatility clustering 534 The ARCH model 535 Simulating an ARCH (1) process 536 The GARCH model 537 Simulating a GARCH process 538 Simulating a GARCH (p,q) process using modified garchSim() 539 GJR_GARCH by Glosten, Jagannanthan, and Runkle 542 References 545
Appendix A – data case 8 - portfolio hedging using VIX calls 545
References 546
Appendix B – data case 8 - volatility smile and its implications 546