source experience distilled PUBLISHING BIRMINGHAM - MUMBAI

Similar documents
INTRODUCTION TO THE ECONOMICS AND MATHEMATICS OF FINANCIAL MARKETS. Jakša Cvitanić and Fernando Zapatero

for Finance Python Yves Hilpisch Koln Sebastopol Tokyo O'REILLY Farnham Cambridge Beijing

Python for Finance. Build real-life Python applications for quantitative finance and financial engineering. Yuxing Yan BIRMINGHAM - MUMBAI

Handbook of Financial Risk Management

CFE: Level 1 Exam Sample Questions

Statistics and Finance

Key Features Asset allocation, cash flow analysis, object-oriented portfolio optimization, and risk analysis

Market Risk Analysis Volume I

Hull, Options, Futures & Other Derivatives Exotic Options

Mathematics of Finance Final Preparation December 19. To be thoroughly prepared for the final exam, you should

Statistical Models and Methods for Financial Markets

ACST829 CAPITAL BUDGETING AND FINANCIAL MODELLING. Semester 1, Department of Actuarial Studies

Contents Critique 26. portfolio optimization 32

Financial Models with Levy Processes and Volatility Clustering

Market Volatility and Risk Proxies

ก ก ก ก ก ก ก. ก (Food Safety Risk Assessment Workshop) 1 : Fundamental ( ก ( NAC 2010)) 2 3 : Excel and Statistics Simulation Software\

Computer Exercise 2 Simulation

An Introduction to Derivatives and Risk Management, 7 th edition Don M. Chance and Robert Brooks. Table of Contents

MFE/3F Questions Answer Key

MÄLARDALENS HÖGSKOLA

palgrave Shipping Derivatives and Risk Management macmiuan Amir H. Alizadeh & Nikos K. Nomikos

Financial Computing with Python

Implied Volatility using Python s Pandas Library

Contents. Part I Introduction to Option Pricing

ExcelSim 2003 Documentation

List of tables List of boxes List of screenshots Preface to the third edition Acknowledgements

Index. High-Frequency Trading Models By Gewei Ye Copyright 2011 by Gewei Ye.

MFIN 7003 Module 2. Mathematical Techniques in Finance. Sessions B&C: Oct 12, 2015 Nov 28, 2015

KARACHI UNIVERSITY BUSINESS SCHOOL UNIVERSITY OF KARACHI BS (BBA) VI

MSc Financial Mathematics

MATH4143: Scientific Computations for Finance Applications Final exam Time: 9:00 am - 12:00 noon, April 18, Student Name (print):

ALGORITHMIC TRADING STRATEGIES IN PYTHON

HANDBOOK OF. Market Risk CHRISTIAN SZYLAR WILEY

Subject CS1 Actuarial Statistics 1 Core Principles. Syllabus. for the 2019 exams. 1 June 2018

Introductory Econometrics for Finance

Sample Size Calculations for Odds Ratio in presence of misclassification (SSCOR Version 1.8, September 2017)

Introducing LIST. Riccardo Bernini Head of Financial Engineering Enrico Melchioni Head of International Sales. March 2018

Chapter 9 - Mechanics of Options Markets

Derivative Securities Fall 2012 Final Exam Guidance Extended version includes full semester

PROBABILITY. Wiley. With Applications and R ROBERT P. DOBROW. Department of Mathematics. Carleton College Northfield, MN

CONTENTS. Introduction. Acknowledgments. What Is New in the Second Edition? Option Pricing Formulas Overview. Glossary of Notations

Modelling for the Financial Markets with Excel

MFE/3F Questions Answer Key

Computational Statistics Handbook with MATLAB

Errata and updates for ASM Exam MFE/3F (Ninth Edition) sorted by page.

Accelerated Option Pricing Multiple Scenarios

NATIONAL UNIVERSITY OF SINGAPORE Department of Finance

The Pennsylvania State University. The Graduate School. Department of Industrial Engineering AMERICAN-ASIAN OPTION PRICING BASED ON MONTE CARLO

Implementing Models in Quantitative Finance: Methods and Cases

MSc Financial Mathematics

The histogram should resemble the uniform density, the mean should be close to 0.5, and the standard deviation should be close to 1/ 12 =

Master s in Financial Engineering Foundations of Buy-Side Finance: Quantitative Risk and Portfolio Management. > Teaching > Courses

yuimagui: A graphical user interface for the yuima package. User Guide yuimagui v1.0

Notes. Cases on Static Optimization. Chapter 6 Algorithms Comparison: The Swing Case

2017 IAA EDUCATION SYLLABUS

Math Option pricing using Quasi Monte Carlo simulation

Table of Contents. Chapter 1 General Principles... 1

Table of Contents. Part I. Deterministic Models... 1

Option Valuation (Lattice)

Queens College, CUNY, Department of Computer Science Computational Finance CSCI 365 / 765 Spring 2018 Instructor: Dr. Sateesh Mane.

Using Fat Tails to Model Gray Swans

AMSTERDAM BOSTON HEIDELBERG LONDON NEW YORK OXFORD PARIS SAN DIEGO SAN FRANCISCO SINGAPORE SYDNEY TOKYO Academic Press is an Imprint of Elsevier

by Kian Guan Lim Professor of Finance Head, Quantitative Finance Unit Singapore Management University

NUMERICAL AND SIMULATION TECHNIQUES IN FINANCE

MATH6911: Numerical Methods in Finance. Final exam Time: 2:00pm - 5:00pm, April 11, Student Name (print): Student Signature: Student ID:

POSSIBILITY CGIA CURRICULUM

Linda Allen, Jacob Boudoukh and Anthony Saunders, Understanding Market, Credit and Operational Risk: The Value at Risk Approach

INSTITUTE OF ACTUARIES OF INDIA

Expected Return Methodologies in Morningstar Direct Asset Allocation

Washington University Fall Economics 487. Project Proposal due Monday 10/22 Final Project due Monday 12/3

ASC 718 Valuation Consulting Services

Analytical Finance 1 Seminar Monte-Carlo application for Value-at-Risk on a portfolio of Options, Futures and Equities

Monte Carlo Simulations

FE570 Financial Markets and Trading. Stevens Institute of Technology

Market Risk Analysis Volume II. Practical Financial Econometrics

CFA Level I - LOS Changes

Downside Risk: Implications for Financial Management Robert Engle NYU Stern School of Business Carlos III, May 24,2004

PRINCIPLES of INVESTMENTS

Risk Video #1. Video 1 Recap

ABSA Technical Valuations Session JSE Trading Division

Trading Volatility Using Options: a French Case

Washington University Fall Economics 487

NATIONAL UNIVERSITY OF SINGAPORE Department of Finance FIN3130: Financial Modeling Semester 1, 2018/2019

Steps for Software to Do Simulation Modeling (New Update 02/15/01)

Options Markets: Introduction

Tuomo Lampinen Silicon Cloud Technologies LLC

UPDATED IAA EDUCATION SYLLABUS

Better decision making under uncertain conditions using Monte Carlo Simulation

APPEND I X NOTATION. The product of the values produced by a function f by inputting all n from n=o to n=n

Regression Analysis and Quantitative Trading Strategies. χtrading Butterfly Spread Strategy

Market Risk Analysis Volume IV. Value-at-Risk Models

Economic Risk and Decision Analysis for Oil and Gas Industry CE School of Engineering and Technology Asian Institute of Technology

Certified Portfolio Manager Course Curriculum

JEM034 Corporate Finance Winter Semester 2017/2018

The Black-Scholes Model

Risk Finance and Asset Pricing

Asset Allocation in the 21 st Century

The following content is provided under a Creative Commons license. Your support

Market risk measurement in practice

MFE Course Details. Financial Mathematics & Statistics

Transcription:

Python for Finance Build real-life Python applications for quantitative finance and financial engineering Yuxing Yan source experience distilled PUBLISHING BIRMINGHAM - MUMBAI

Table of Contents Preface 1 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 Rinding the help window 18 Finding manuals and tutorials 19 Rinding 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

Table of Contents 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 Rinding 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 [ü]

lable of Contents 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 Rinding out all built-in modules 85 Rinding out all the available modules 86 Rinding the location of an imported module 87 More Information about modules 88 Rinding 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

Table of Contents 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 Rinding a function from an imported module 116 Understanding optimization 116 Linear regression and Capital Assets Pricing Model (CAPM) 117 Retrieving data from an externa! 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

lable of Contents 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 fite 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 Data Frame 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

Table of Contents 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 [vi]

lable of Contents Butterfly with calls 256 Relationship between input values and option vaiues 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

lable of Contents 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 ofannual returns 319 Simulation of stock price movements 320 Graphical presentation of stock prices at options' maturity dates 322 Rinding an efficient portfolio and frontier 324 Rinding an efficient frontier based on two stocks 324 Impact of different correlations 326 Constructing an efficient frontier with n stocks 329 Geometrie 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

lable of Contents The ARCH model 363 Simulating an ARCH (1) process 364 The GARCH (Generalized ARCH) model 365 Simulating a GARCH process 366 Simulating a GARCH (p,q) process using modified garchsim() 367 GJR_GARCH by Glosten, Jagannanthan, and Runkle (1993) 369 Summary 373 Exercises 373 Index 375