Python for Finance: Analyze Big Financial Data

(Elle) #1

Python Syntax


One really helpful feature of Spyder as an integrated development environment is its


automatic syntax and code checking, which checks Python code for compliance with the


PEP 8 recommendations for Python syntax. But what is codified in “Python Enhancement


Proposal 8”? Principally, there are some code formatting rules that should both establish a


common standard and allow for better readability of the code. In that sense, this approach


is not too dissimilar from a written or printed natural language where certain syntax rules


also apply.


For example, consider the code in Example 1-1 of Chapter 1 for the valuation of a


European call option via Monte Carlo simulation. First, have a look at the version of this


code in Example A-1 that does not conform to PEP 8. It is rather packed, because there are


blank lines and spaces missing (sometimes there are also too many spaces or blank lines).


Example A-1. A Python script that does not conform to PEP 8


Monte Carlo valuation of European call option


in Black-Scholes-Merton model


bsm_mcs_euro_syntax_false.py


import numpy as np
#Parameter Values
S0=100.#initial index level
K=105.#strike price
T= 1.0#time-to-maturity
r=0.05#riskless short rate
sigma =0.2#volatility
I= 100000 # number of simulations


Valuation Algorithm


z=np.random.standard_normal(I)#pseudorandom numbers
ST=S0np.exp((r- 0.5sigma* 2 )+sigmasqrt(T)* z)#index values at maturity


hT=np.maximum(ST-K, 0 )#inner values at maturity
C0=np.exp(-rT)sum(hT)/I# Monte Carlo estimator


Result Output


print“Value of the European Call Option %5.3f”%C0


Now, take a look at the version in Example A-2 that conforms to PEP 8 (i.e., exactly the


one found in Example 1-1). The main difference in readability stems from two facts:


Use of blank lines to indicate code blocks


Use of spaces around Python operators (e.g., = or *) as well as before any hash


character for comments (here: two spaces)


Example A-2. A Python script that conforms to PEP 8



Monte Carlo valuation of European call option


in Black-Scholes-Merton model


bsm_mcs_euro_syntax_correct.py



import numpy as np


Parameter Values


S0 = 100. # initial index level
K = 105. # strike price
T = 1.0 # time-to-maturity
r = 0.05 # riskless short rate
sigma = 0.2 # volatility


I = 100000 # number of simulations

Free download pdf