Python and Finance: Why Use Python for Finance
1.3.1 Finance and Python syntax
Most people who take their first steps in using Python in a financial environment are likely to be tackling some algorithmic problem. This is similar to the scientist who wants to solve differential equations, find integrals, or visualize certain data. In general, there is not much demand for formal development processes, testing, documentation, or deployment at this stage. However, this phase seems to be when people fall in love with Python in particular, mainly because Python’s syntax in general is fairly close to the mathematical syntax used to describe scientific problems or financial algorithms.
We can illustrate this phenomenon with a simple financial algorithm – estimating the value of a European call option by means of a Monte Carlo simulation. We will consider the Black-Scholes-Merton (BSM) model, in which the potential risk of the option follows a geometric Brownian motion.
It is assumed that we use the following numerical parameters for valuation.
initial stock index level S0 = 100.
the strike price K=105 for the European call option.
maturity time T=1 year.
fixed risk-free short-term interest rate r=5%.
fixed volatility σ=20%.
In the BSM model, the level of the expiration index is a random variable given by Equation 1-1, where z is a standard normally distributed random variable.
Equation 1-1 Black-Scholes-Merton (1973) Expiration Index Level
The following is an algorithmic description of the Monte Carlo valuation process.
(1) Obtain I (pseudo) random numbers z(i) from a standard normal distribution, i ∈ {1, 2, …, I}.
(2) Compute all expiration index levels ST(i) for the given z(i) and Equation 1-1.
(3) Calculate all intrinsic values hT(i)=max(ST(i)-K,0) for the expiration period right.
(4) Estimate the present value of the option through the Monte Carlo estimation function given in Equation 1-2.
Equation 1-2 Monte Carlo estimation function for Euclidean options
Now, we need to translate this problem and algorithm into Python code. The following code will implement some of the necessary steps.
In [6]: import math
import numpy as np ❶
In [7]: S0 = 100. ❷
K = 105. ❷
T = 1.0 ❷
r = 0.05 ❷
sigma = 0.2 ❷
In [8]: I = 100000 ❷
In [9]: np.random.seed(1000) ❸
In [10]: z = np.random.standard_normal(I) ❹
In [11]: ST = S0 * np.exp((r – sigma ** 2 / 2) * T + sigma * math.sqrt(T) * z) ❺
In [12]: hT = np.maximum(ST – K, 0) ❻
In [13]: C0 = math.exp(-r * T) * np.mean(hT) ❼
In [14]: print(‘Value of the European call option: {:5.3f}.’ .format(C0)) ❽
Value of the European call option: 8.019.
❶ NumPy is used here as the main program package.
❷ Define the model and simulate the parameter values.
❸ The random number generator seed value is fixed.
❹ Extract standard normally distributed random numbers.
❺ Simulate the end-of-period values.
❻ Calculate the option maturity return.
❼ Calculate the Monte Carlo estimation function.
❽ Print out the estimation result.
The following 3 aspects are worth noting.
Syntax
Python syntax is quite close to mathematical syntax, such as the aspect of parameter assignment.
Translation
Each mathematical or algorithmic statement can generally be translated into a single line of Python code.
Vectorization
One of the strengths of NumPy is the compact vectorization syntax, which allows, for example, 100,000 calculations to be performed in a single line of code.
This code can be used in interactive environments such as IPython or Jupyter Notebook. However, code that needs to be reused frequently is generally organized as so-called modules (or scripts), which are Python (text) files with a .py suffix. The module for this example is shown in Example 1-1, and can be saved as a file named bsm_msc_euro.py.
Example 1-1 Monte Carlo Valuation of a European Call Option
#
# Monte Carlo valuation of European call option
# in Black-Scholes-Merton model
# bsm_mcs_euro.py
#
# Python for Finance, 2nd ed.
# (c) Dr. Yves J. Hilpisch
# in
import math
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) # pseudo-random numbers
# index values at maturity
ST = S0 * np.exp((r – 0.5 * sigma ** 2) * T + sigma * math.sqrt(T) * z)
hT = np.maximum(ST – K, 0) # payoff at maturity
C0 = math.exp(-r * T) * np.mean(hT) # Monte Carlo estimator
# Result Output
print(‘Value of the European call option %5.3f.’ % C0)
The simple algorithm example in this subsection illustrates that Python’s basic syntax is well suited to complement the classic scientific language duo of English and mathematics. Adding Python to a portfolio of scientific languages can make it even more comprehensive. We now have.
for writing and talking about science, finance, and other issues in English.
mathematics for succinctly and precisely describing and modeling abstract features, algorithms, complex numbers, etc.
Python for technically modeling and implementing abstract features, algorithms, complex numbers, etc.
Mathematics and Python syntax
There is hardly any programming language that comes as close to mathematical syntax as Python. As a result, numerical algorithms are easily translated from mathematical representations to Python implementations. With Python, we can prototype, develop, and maintain code in these domains efficiently.
In some domains, it is common practice to use pseudocode, which introduces a 4th language family member. As an example, the task of pseudocode is to represent financial algorithms in a more technical way, close not only to the mathematical representation, but also to the technical implementation. In addition to the algorithm itself, the pseudocode takes into account the working principles of the computer.
This approach is generally adopted because, with most programming languages, the distance between the technical implementation and the formal mathematical representation is quite “distant”. Most programming languages must contain many elements that are only technically necessary, but it is difficult to see the equivalent in mathematics and code.
Today, Python is often used as pseudocode because its syntax is similar to mathematics and the technical “overhead” can be kept to a minimum. This is achieved through the high-level concepts embodied in the language, which not only have their advantages, but also entail risks and other costs. But to be sure, we can use Python as the need arises, following from the outset the rigorous implementation and coding methods that other languages might require. In this sense, Python can provide the best balance between two worlds: high level abstraction and strict implementation.