Transcription of Mastering Python for Finance - palmislandtraders.com
1 Mastering Python for FinanceUnderstand, design, and implement state-of-the-art mathematical and statistical applications used in Finance with PythonJames Ma WeimingBIRMINGHAM - MUMBAIM astering Python for FinanceCopyright 2015 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals.
2 However, Packt Publishing cannot guarantee the accuracy of this published: April 2015 Production reference: 1240415 Published by Packt Publishing Place35 Livery StreetBirmingham B3 2PB, Ma WeimingReviewersNamit KewatMarco MarchioroJiri PikSteven E. Sommer, MD, MBAC ommissioning EditorUsha IyerAcquisition EditorUsha IyerContent Development EditorSusmita SabatTechnical EditorPrajakta MhatreCopy EditorRashmi SawantProject CoordinatorMilton DsouzaProofreadersStephen CopestakeSafis EditingPaul HindleIndexerHemangini BariGraphicsSheetal AuteValentina D'silvaDisha HariaAbhinash SahuProduction CoordinatorAparna BhagatCover WorkAparna BhagatAbout the AuthorJames Ma Weiming works with high-frequency, low-latency trading systems, writing his own programs and tools, most of which are open sourced. He is currently supporting veteran traders in the, trading pits of the Chicago Board of Trade devising strategies to game the market.
3 He graduated from the Stuart School of Business at Illinois Institute of Technology with a master of science degree in started his career in Singapore after receiving his bachelor's degree in computer engineering from Nanyang Technological University and diploma in information technology from Nanyang Polytechnic. During his career, he has worked in treasury operations handling foreign exchange and fixed income products. He also developed mobile applications with a company operating a funds and investments distribution book was made possible by the fabulous team at Packt Publishing, especially Usha Iyer and Susmita Sabat. I am also eminently grateful to all the reviewers for their comments and to my immediate family for their encouragement and good 'd like to thank Milt Robinson, Brian Hickman, and Frank for their mentorship on the trading the ReviewersNamit Kewat is a financial analyst and XBRL expert.
4 He uses Python for his requirements related to financial reporting, from extracting data to its validation, and from recording to reporting. In his spare time, he enjoys working on web projects, machine learning experiments on SEC/HMRC XBRL financial data, and spending time with his Marchioro is the CEO of Quant Island, a Singapore-based consultancy firm specialized in quantitative risk models for asset management and energy Finance . He has 15 years of experience in quantitative financial risk management, where his areas of expertise range from quantitative risk modeling and agile software development, to risk training. As a founding partner of RiskMap, he was one of the three creators of QuantLib, a widely-used open source library for financial modeling. He has extensive experience in quantitative Finance , where he is well-versed with the end-to-end process of developing financial software.
5 Prior to moving to Singapore, he held various senior roles in StatPro, covering the risk-management software development cycle. As the head of the quantitative research team, he was responsible for creating original risk models that have been successively and quickly implemented in an agile software environment. From 2010 to 2014, he held the position of an adjunct professor at the University of Milano-Bicocca, where he taught complex derivatives to a highly-ranked graduate Pik is a Finance and business intelligence consultant, working with major investment banks, hedge funds, and other financial players. He has architected and delivered breakthrough trading, portfolio and risk management systems, and decision support systems across a number of 's consulting firm, WIXESYS, provides its clients with certified expertise, judgment, and execution at the speed of light.
6 WIXESYS' power tools include revolutionary Excel and Outlook add-ons, available at E. Sommer, MD, MBA is a physician who has practiced critical care medicine for over 24 years. He is the chief investment officer for a small hedge fund, where he has employed portfolio optimization models based on volatility, modern portfolio theory, and market regime to drive asset selection and market exposure decisions. He has extensively employed R and Python to leverage big data in the development of his investment Sommer holds a BA degree from Lafayette College, where he graduated Magna Cum Laude with honors in chemistry, an MD degree from Drexel University School of Medicine, where he graduated with distinction in medicine, an MBA degree from the University of Virginia's Darden School of Business, and a certificate in computational Finance with distinction from the Georgia Institute of files, eBooks, discount offers, and moreFor support files and downloads related to your book, please visit you know that Packt offers eBook versions of every book published, with PDF and ePub files available?
7 You can upgrade to the eBook version at and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more , you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browserFree access for Packt account holdersIf you have an account with Packt at , you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
8 [ i ]Table of ContentsPreface ixChapter 1: Python for Financial Applications 1Is Python for me? 2 Free and open source 2 High-level, powerful, and flexible 3A wealth of standard libraries 3 Objected-oriented versus functional programming 3 The object-oriented approach 4 The functional approach 4 Which approach should I use? 5 Which Python version should I use? 5 Introducing IPython 6 Getting IPython 6 Using pip 6 The IPython Notebook 7 Notebook documents 8 Running the IPython Notebook 8 Creating a new notebook 8 Notebook cells 9 Code cell 10 Markdown cell 10 Raw NBConvert cell 10 Heading cells 10 Simple exercises with IPython Notebook 11 Creating a notebook with heading and Markdown cells 11 Saving notebooks 12 Mathematical operations in cells 13 Displaying graphs 13 Inserting equations 14 Displaying images 15 Inserting YouTube videos 16 Table of Contents[ ii ]Working with HTML 17 The pandas DataFrame object as an HTML table 17 Notebook for Finance 18 Summary 19 chapter 2.
9 The Importance of Linearity in Finance 21 The capital asset pricing model and the security market line 22 The Arbitrage Pricing Theory model 27 Multivariate linear regression of factor models 27 Linear optimization 29 Getting PuLP 29A simple linear optimization problem 30 Outcomes of linear programs 32 Integer programming 32An example of an integer programming model with binary conditions 33A different approach with binary conditions 35 Solving linear equations using matrices 37 The LU decomposition 38 The Cholesky decomposition 40 The QR decomposition 42 Solving with other matrix algebra methods 43 The Jacobi method 44 The Gauss-Seidel method 46 Summary 48 chapter 3: Nonlinearity in Finance 49 Nonlinearity modeling 50 Examples of nonlinear models 50 The implied volatility model 50 The Markov regime-switching model 52 The threshold autoregressive model 53 Smooth transition models 54An introduction to root-finding 55 Incremental search 56 The bisection method 58 Newton's method 61 The secant method 63 Combining root-finding methods 66 SciPy implementations 66 Root-finding scalar functions 67 General nonlinear solvers 68 Summary 70 Table of Contents[ iii ] chapter 4: Numerical Procedures 71 Introduction to options 72 Binomial trees in options pricing 72 Pricing European options 73 Are these formulas relevant to stocks?
10 What about futures? 75 Writing the StockOption class 76 Writing the BinomialEuropeanOption class 77 Pricing American options with the BinomialTreeOption class 79 The Cox-Ross-Rubinstein model 82 Writing the BinomialCRRO ption class 82 Using a Leisen-Reimer tree 83 Writing the BinomialLROption class 85 The Greeks for free 86 Writing the BinomialLRWithGreeks class 88 Trinomial trees in options pricing 90 Writing the TrinomialTreeOption class 91 Lattices in options pricing 93 Using a binomial lattice 94 Writing the BinomialCRRO ption class 94 Using the trinomial lattice 96 Writing the TrinomialLattice class 97 Finite differences in options pricing 98 The explicit method 100 Writing the FiniteDifferences class 101 Writing the FDExplicitEu class 103 The implicit method 105 Writing the FDImplicitEu class 106 The Crank-Nicolson method 108 Writing