QF205 Week 10

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 137

Slide

001
001/137
QF205 - Computing Technology For Finance
Week 10

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Preparations
Dr. Zhao Yibao  Get your laptop ready.
Senior Lecturer
Of Quantitative
 Launch Jupyter notebook and open “QF205 Notebook WK10.ipynb”.
Finance
Slide
002
002/137
Quick Review of Week 09

 Classes
 Class Attributes and Instance Attributes
 Instance Methods, Class Methods and Static
QF205
Methods COMPUTING
TECHNOLOGY
 Scope and Namespace (Functions vs Classes) FOR FINANCE

 Inheritance
 Private Attributes
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
003
001/137
This week, we’ll explore Numpy, Pandas and
Matplotlib and their applications in

 Stock Chart and Moving Average Crossover


QF205
COMPUTING
TECHNOLOGY  Option Pricing by the Binomial Tree
FOR FINANCE

Method (revisited)

Dr. Zhao Yibao


 Option Pricing by the Monte Carlo Method
Senior Lecturer
Of Quantitative
Finance
Slide
004
002/137

 How to import/export data from/to an


Excel file?
 How to write results to an Excel file? QF205
COMPUTING
 How to import data from a csv file? TECHNOLOGY
FOR FINANCE

 How to import data from an HTML file?


 How to manipulate DataFrame/Series?
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
005
002/137

 How to manipulate ndarray? QF205


COMPUTING
TECHNOLOGY

 How to generate random numbers? FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
006
002/137

 How to plot a stock price (line) chart?


QF205
 How to plot a stock prices OHLC COMPUTING
TECHNOLOGY
FOR FINANCE

candlestick chart?

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
007
002/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
008
001/137

stock line chart


Moving Average Crossover
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
.csv
Finance
01 # Moving Average Crossover Slide
02 import pandas as pd 009
002/137
03 import numpy as np
04 import matplotlib.pyplot as plt
05 plt.rcParams["figure.figsize"]=[12,8] # (optional)
06 data=pd.read_csv('CC3.SI.csv',index_col=0)
07 data.drop(data.index[data['Volume']==0],inplace=True)
08 data['15d']= np.round(data['Close'].rolling(window=15).mean(),3)
09 data['50d']= np.round(data['Close'].rolling(window=50).mean(),3)
10 x=data['15d']-data['50d']
11 x[x>0]=1 AppMovingAverageCrossover.py

21 lines
12 x[x<=0]=0 QF205
13 y=x.diff() COMPUTING
14 idxSell=y.index[y<0] TECHNOLOGY
FOR FINANCE
15 idxBuy=y.index[y>0]
16 data['crossSell']=np.nan
17 data.loc[idxSell,'crossSell']=data.loc[idxSell,'Close']
18 data['crossBuy']=np.nan
19 data.loc[idxBuy,'crossBuy']=data.loc[idxBuy,'Close']
20 data[['Close', '15d', '50d','crossSell','crossBuy']].plot( Dr. Zhao Yibao
style=['k-','b-','c-','ro','yo'],linewidth=1) Senior Lecturer
21 plt.show() Of Quantitative
Finance
Slide
010
002/137
 Read a CSV (comma-separated) file into DataFrame (pandas.read_csv)
 Comparison operators on DataFrame, Series and Numpy ndarrays
 Logical operators on DataFrame, Series and Numpy ndarrays
 Drop rows and columns in DataFrame (pandas.DataFrame.drop)
 DataFrame and Series
 Rolling window calculations (pandas.Series.rolling)
QF205
 Subtract two Series (-) COMPUTING
TECHNOLOGY
 Boolean indexing FOR FINANCE

 Assignment statements
 1st discrete difference of a Series (Series.diff)
 DataFrame indexing and selection Dr. Zhao Yibao
Senior Lecturer
 Make plots of DataFrame using matplotlib (pandas.DataFrame.plot) Of Quantitative
Finance
Slide
011
002/137

QF205
*** COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
012
001/137 import … as …

02 import pandas as pd
QF205
03 import numpy as np
COMPUTING
TECHNOLOGY
04 import matplotlib.pyplot as plt
FOR FINANCE

plt.rcParams["figure.figsize"]=[12,8]
(Dr. Z: plt has an attribute rcParams, which is a dictionary-like object.)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
013
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


pd.read_csv
Senior Lecturer
Of Quantitative
Finance
Slide
014
001/137 pd.read_csv https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

Read CSV (comma separated values) file into DataFrame


pandas.read_csv(filepath_or_buffer, sep=', ', delimiter=None,
header='infer', names=None, index_col=None, usecols=None,
squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None,
1
engine=None, 2
converters=None, 3
true_values=None, false_values=None,
skipinitialspace=False, skiprows=None, nrows=None, na_values=None,
keep_default_na=True, na_filter=True, verbose=False,
skip_blank_lines=True, parse_dates=False,
QF205 infer_datetime_format=False, keep_date_col=False, date_parser=None,
COMPUTING
TECHNOLOGY 4
dayfirst=False, iterator=False, chunksize=None,
FOR FINANCE compression='infer', thousands=None, decimal=b'.',
lineterminator=None, quotechar='"', quoting=0, escapechar=None,
comment=None, encoding=None, dialect=None, tupleize_cols=False,
error_bad_lines=True, warn_bad_lines=True, skipfooter=0,
skip_footer=0, doublequote=True, delim_whitespace=False,
as_recarray=False, compact_ints=False, use_unsigned=False, (Dr. Z: Is there
Dr. Zhao Yibao low_memory=True, buffer_lines=None, memory_map=False,
Senior Lecturer float_precision=None) a *- or **-
Of Quantitative
Finance
Do Not Test parameter?)
Slide
015
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Do Not Test
Slide
016
001/137 data=pd.read_csv('CC3.SI.csv', header='infer')
 header=0

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

dataframe
header='infer'

header=0, w/o name


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative Do Not Test
Finance
Slide
017
001/137 data=pd.read_csv('CC3.SI.csv', header=None)

QF205
COMPUTING
TECHNOLOGY

dataframe
FOR FINANCE

header=None
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative Do Not Test
Finance
Slide
data=pd.read_csv('CC3.SI.csv', names=range(7,0,-1))
018
001/137
 header=None

QF205
COMPUTING

dataframe
TECHNOLOGY
FOR FINANCE

names=range(7,0,-1)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide data=pd.read_csv('CC3.SI.csv', header=0, names=range(7,0,-1))
019
001/137

QF205
COMPUTING
TECHNOLOGY
header=0
+
FOR FINANCE

names=range(7,0,-1)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Do Not Test
Finance
Slide
020
001/137

QF205
COMPUTING (A) data=pd.read_csv('CC3.SI.csv', header=0, names=range(7,0,-1))
TECHNOLOGY
FOR FINANCE
(B) data=pd.read_csv('CC3.SI.csv', names=range(7,0,-1))

(C) data=pd.read_csv('CC3.SI.csv', header=0)

Dr. Zhao Yibao (D) data=pd.read_csv('CC3.SI.csv')


Senior Lecturer
Of Quantitative
Finance
Slide
021
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


index_col=0
Senior Lecturer
Of Quantitative
Finance
Do Not Test
Slide
022
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer Do Not Test
Of Quantitative
Finance
Slide
023
001/137 DataFrame (data)
data.columns

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

data.index

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
024
001/137

QF205

pandas.Index:
COMPUTING
TECHNOLOGY
FOR FINANCE
 Indexing
 Slicing
 list-like object (Python)
 array-like object, 1-D (Numpy)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
025
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


 Indexing pandas.Index: list-like/array-like
Senior Lecturer
Of Quantitative
 Slicing
 slide 38
Finance
Slide
026
001/137
data['Open'] data['Adj Close']
syntactic sugar data.Open

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
027
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

This is a Series. This is a Series.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
028
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
029
001/137

 pandas.Series: One-dimensional
ndarray with axis labels.
 pandas.DataFrame: Two-
dimensional size-mutable, tabular
QF205
COMPUTING
data structure with labeled axes
TECHNOLOGY
FOR FINANCE (rows and columns). Can be
thought of as a dict-like container
for Series objects.
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
030
001/137

DataFrame[colname]:

Series corresponding to
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
colname
(Example: data['Open'])
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
031
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
032
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Do Not Test parse_dates=True
Slide
033
001/137

data.values
(numpy.ndarray)
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide DataFrame.drop(labels, axis=0, level=None, inplace=False, errors='raise')
034
001/137 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html

data.drop(data.index[data['Volume']==0],inplace=True)

Drop a row.
QF205
COMPUTING
TECHNOLOGY
Do Not Test
FOR FINANCE
Volume=0

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
035
001/137 data.drop(data.index[data['Volume']==0],inplace=True)

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao data['Volume']


Senior Lecturer
Of Quantitative
Finance
is a Series.
Slide
036
001/137 data.drop(data.index[data['Volume']==0],inplace=True)

data['Volume'] is a Series.
data['Volume']==0
QF205
COMPUTING
returns a Series of True and
TECHNOLOGY
FOR FINANCE False with the same labels.
Comparison between
a Series and a scalar
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
results a Series.
Finance
Slide
Boolean Indexing (Dr. Z: Does myList support it?
See Week 10 Extra Exercise.)
037
002/137

Lists do not support


Boolean indexing.

Numpy ndarrays
support Boolean QF205
COMPUTING
indexing. TECHNOLOGY
FOR FINANCE

Serieses also
support Boolean
indexing.
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
038
001/137 data.drop(data.index[data['Volume']==0],inplace=True)
data.index

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative Do Not Test
Finance
Slide data.drop(data.index[data['Volume']==0],inplace=True)
039
001/137

Do Not Test

It’s gone!
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

If using “inplace=False”,
Dr. Zhao Yibao we’ll get a copy. data will
Senior Lecturer
Of Quantitative remain unchanged.
Finance
Slide
040
001/137

(default value) Do Not Test


QF205
COMPUTING DataFrame.drop(labels, axis=0)
TECHNOLOGY
FOR FINANCE
0/'index'
DataFrame.drop(labels, axis=1)
Dr. Zhao Yibao 1/'columns'
Senior Lecturer
Of Quantitative
Finance
Slide
Series.rolling(window, min_periods=None, freq=None,
041
001/137
center=False, win_type=None, on=None, axis=0,
Do Not Test
closed=None)

Provides rolling window calculations. (.sum(), .mean(), …)


data['15d']= np.round(data['Close'].rolling(window=15).mean(),3)
data['50d']= np.round(data['Close'].rolling(window=50).mean(),3)

QF205
COMPUTING
We cannot use the “dot notation”
TECHNOLOGY
FOR FINANCE to add a column to a DataFrame.
data['15d']= np.round(data['Close'].rolling(15).mean(),3)
data['50d']= np.round(data['Close'].rolling(50).mean(),3)

Dr. Zhao Yibao  Series.rolling  Rolling Object


Senior Lecturer
Of Quantitative  RollingObject.mean()  Series
Finance
Slide
042
001/137

Two columns
QF205
COMPUTING
TECHNOLOGY
were added.
FOR FINANCE

dict-like
(Dr. Z: How to add
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
a new item in a
dictionary?)
NaN?
Finance
Slide
043
002/137
1
2
3
4
5 NaN is a float-type number.
6
7 Value comparison with an
8 NaN will always result a QF205
COMPUTING
9 False. TECHNOLOGY
10 FOR FINANCE

11 Any arithmetic operation


12 on an NaN will result NaN.
13
(Dr. Z: Why!? Why!? Can we just
14
return those non-NaN values?) Dr. Zhao Yibao
15
Senior Lecturer
.rolling(15).mean() Of Quantitative
Finance
Slide
044
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
np.round(Series, 3)

Series.round(3)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
045
001/137

Subtraction of Two Series


(having the same labels)
(Dr. Z: What if they have different labels?)
QF205

x: pandas.core.series.Series
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
046
001/137

 Boolean Indexing
 Assignment

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
047
001/137 Series.diff(periods=1, axis=0)
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html

Do Not Test
QF205
COMPUTING
Series.diff
TECHNOLOGY
FOR FINANCE
returns a Series of
the same length
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
(and same labels).
Finance
Slide
048
001/137

 Boolean Indexing
QF205
COMPUTING
 np.logical_or
(element-wise or)
TECHNOLOGY
FOR FINANCE

Do Not Test
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
049
001/137

 y is a Series
 y.index is DatetimeIndex type
 Boolean Indexing

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

 idxBuy
 idxSell
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
050
001/137

 np.nan
Another
QF205
column is
COMPUTING
TECHNOLOGY
FOR FINANCE
created.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
051
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
data['Close'][idxSell]

Dr. Zhao Yibao


Senior Lecturer
chained indexing: copy or reference?
Of Quantitative
Finance
Slide
052
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE data[idxSell]['Close']
Q: Will the above work too?
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
A: No.
Finance
Slide
053
001/137

In a pandas.DataFrame,
QF205
COMPUTING
rows and columns use
different indexing methods.
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
054
001/137

 Chained Index

 .loc Indexing
 Assignment

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
055
001/137
Similarly,
'crossBuy'

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
Do Not Test 056
002/137
DataFrame.plot(x=None,
y=None, kind='line',
ax=None, subplots=False,
sharex=None,
sharey=False,
layout=None,
figsize=None,
use_index=True,
title=None, grid=None,
legend=True, style=None, QF205
logx=False, logy=False, COMPUTING
loglog=False, TECHNOLOGY
xticks=None, yticks=None, FOR FINANCE

xlim=None, ylim=None,
rot=None, fontsize=None,
colormap=None,
table=False, yerr=None,
xerr=None,
secondary_y=False, Dr. Zhao Yibao
sort_columns=False, Senior Lecturer
**kwds) Of Quantitative
Finance
Slide
057
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
Fancy Indexing:
Using a list of
column names as
the index of a
Dr. Zhao Yibao
Senior Lecturer DataFrame results
Of Quantitative
Finance
a DataFrame.
Slide
058
001/137
https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.show.html

Do Not Test

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
059
001/137

That’s all for the


QF205
COMPUTING
TECHNOLOGY
explanation of the
sample code.
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
060
001/137
Next, … Do Not Test

candlestick_ohlc

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

fill_between
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
061
001/137
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.fill_between.html

x, y1, y2=0
QF205
COMPUTING
TECHNOLOGY
**kwargs
FOR FINANCE

plt

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Do Not Test
Slide
062
001/137
https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.fill_between.html

Do Not Test Another fill_between.

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
063
001/137

List also can! 


y1 can also be a
scalar! 

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative Do Not Test
Finance
Slide
064
001/137
**kwargs

alpha

QF205
COMPUTING color
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao Do Not Test


Senior Lecturer
Of Quantitative
Finance
Slide
065
001/137 x y1 y2
# fill_between
import pandas as pd
They are Serieses.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"]=[12,8] # (optional)

data=pd.read_csv('CC3.SI.csv',index_col=0,parse_dates=True)
data.drop(data.index[data['Volume']==0],inplace=True)

ma=data['Close'].rolling(15).mean()
QF205 mstd=data['Close'].rolling(15).std()
COMPUTING
TECHNOLOGY
FOR FINANCE plt.plot(data.index, data['Close'], 'k')
plt.plot(ma.index, ma, 'b')
plt.fill_between(mstd.index, ma-2*mstd, ma+2*mstd,
color='b', alpha=0.2)
plt.show()
Dr. Zhao Yibao
Senior Lecturer (Dr. Z: Do not panic if you see any warning message. Simply amend the code according to the suggestion in
Of Quantitative the warning message.)
Finance
Slide
066
001/137

objectName: checkbox_ma objectName: checkbox_mstd

layoutName: verticalLayout
Do Not Test
 1 label
QF205
 2 checkbox
COMPUTING
TECHNOLOGY
 1 axes
FOR FINANCE

GUI
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
PyQt5
Slide
067
001/137 Do Not Test

QF205
a .ui file +
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao PyQT5 template.py


Senior Lecturer
Of Quantitative
Finance
Slide
068
001/137

QF205 Template for adding a figure in a GUI.


COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
069
001/137

self

ax1
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

(Dr. Z: The rest is to add an axes in a


figure in a canvas widget in the
Dr. Zhao Yibao verticalLayout in the QMainWindow.)
Senior Lecturer
Of Quantitative
Finance
Slide
070
001/137 Do Not Test
self
 self.plot2
 self.plot3

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

plt.setp
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
visible
Finance
Slide
071
001/137 https://matplotlib.org/api/finance_api.html#matplotlib.finance.candlestick_ohlc

A sequence
of sequences.
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
072
001/137

Do Not Test
fig=plt.figure()
1
ax=plt.axes()
2

QF205 3
COMPUTING
TECHNOLOGY
FOR FINANCE

(Dr. Z: Can we develop a GUI for this?)

1. Use .subplots() to return an ax, or ...


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
ax 2. Use date2num to convert dates to float days
3. Use zip to create the sequence of tuples.
Finance
Slide
073
001/137 Challenge: Modify “AppFillBetween.ui” (using Qt Designer)
and the code “AppFillBetweenUI.py” to obtain the same GUI
as shown in the following two slides. References:
 http://doc.qt.io/qt-5/qfiledialog.html
from PyQt5.QtWidgets import QFileDialog  https://pythonspot.com/pyqt5-file-dialog/

QFileDialog.getOpenFileName
options = QFileDialog.Options()
QF205 options |= QFileDialog.DontUseNativeDialog
COMPUTING
TECHNOLOGY fname, _ = QFileDialog.getOpenFileName(self,'Open file',
FOR FINANCE os.getcwd(),'CSV(*.csv)')

filename (string type) Do Not Test


Q: What if I use the following?
Dr. Zhao Yibao
Senior Lecturer fname = QFileDialog.getOpenFileName(self,'Open file',
Of Quantitative os.getcwd(),'CSV(*.csv)')
Finance
Slide
074
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative (Clicking on “Load Data” button, followed by choosing another csv file, say S68.SI.csv, we obtain another plot.)
Finance
Slide
075
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
076
001/137

Next, let’s learn


QF205
COMPUTING
some basics of
Numpy and Pandas.
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
077
001/137
Learning Outcomes:
ndarrays and DataFrames/Serieses
 Creation
QF205
COMPUTING
TECHNOLOGY
 Indexing and Slicing
FOR FINANCE
 Assignment
 Some Operations
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
 Some Functions
Finance
Slide

Python
078
001/137

Numpy
Error!
QF205
COMPUTING
Error!
TECHNOLOGY
FOR FINANCE Error!
False

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Pandas Solution:
 List comprehension
Slide

Python
079
001/137

QF205
Numpy
COMPUTING
TECHNOLOGY Error!
FOR FINANCE

Numpy has multi-dimensional arrays and


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Pandas supports vectorized computation.
Finance
Slide
080
002/137

numpy.ndarray

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

multi-Dimensional
1D, 2D, 3D, …, n-D, … Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
081
001/137 https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html

numpy.array
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
082
002/137

1 2
3 4 QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
numpy.ndarray
multi-Dimensional
1D, 2D, 3D, …, n-D, … Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
083
001/137
Python
1 2
3 4
QF205
COMPUTING
Numpy DataFrame
TECHNOLOGY
FOR FINANCE (2D only)

Series
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Pandas (1D only)
Slide https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html
084
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
085
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

1 2
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
3 4
Finance
Slide
086
001/137

QF205
COMPUTING
TECHNOLOGY
Indexing & Slicing
FOR FINANCE

(for Numpy ndarray and Pandas DataFrame/Series)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide

Q: What is the output? (Indexing vs Slicing)


087
001/137

0 1 2
3 4 5
6 7 8
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
088
001/137

multidimensional indexing

Error

QF205 boolean indexing


COMPUTING
TECHNOLOGY
FOR FINANCE
Error

fancy indexing

Error
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
089
001/137

multidimensional indexing
multidimensional slicing
QF205
COMPUTING
TECHNOLOGY
boolean indexing
FOR FINANCE
fancying indexing
combined indexing

Dr. Zhao Yibao Indexing & Slicing (numpy.ndarray)


Senior Lecturer
Of Quantitative https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html
Finance
Slide
090
001/137

QF205
x[1]
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
x[[1]]
Finance
Slide
Copy or View? (list) 091
002/137

y=x[1:3]
y is a copy.
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

y changed, but x didn’t.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
092
002/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Hint: For a list x, x[1:3] is a copy. Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
Copy or View? (1D ndarray) 093
002/137

y=x[1:3]
y is a view. QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
y changed, x also.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
094
002/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Hint: For a numpy array x, x[1:3] is a view. Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
y (slicing of the 095
002/137

ndarray x) is a view;

z (fancy indexing of
the ndarray x) is a QF205
COMPUTING

copy.
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
096
001/137

x[:2][0]=100
QF205
COMPUTING
(Dr. Z: This is called chained indexing. It is difficult to
TECHNOLOGY
FOR FINANCE tell whether the assignment happens to a copy or a
view of x. It depends on the implementation of
__getitem__ and __setitem__. So, we won’t explore
Dr. Zhao Yibao
further what will happen on it.)
Senior Lecturer
Of Quantitative
Finance
Slide
097
001/137 https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-and-selecting-data

DataFrame
 Selection via [ ]
 Selection by Position (.iloc)
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

 Selection by Label (.loc)


Dr. Zhao Yibao
Senior Lecturer
 Boolean Indexing
Of Quantitative
Finance
Slide
098
001/137

1
QF205
COMPUTING
2
TECHNOLOGY 3
FOR FINANCE
4
5

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
099
001/137
1
DataFrame

Indexing:
column
2 +
Series

Fancy indexing:
column
QF205
COMPUTING
3 +
TECHNOLOGY DataFrame
FOR FINANCE

4 Slicing: row + DataFrame

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
6 [ ]
Finance
Slide
100
001/137
ndarray DataFrame

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

(Dr. Z: DataFrames use .loc and .iloc for multidimensional indexing.)


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
101
001/137
.iloc integer position based

indexing
QF205 fancy indexing
COMPUTING
TECHNOLOGY
FOR FINANCE slicing

Boolean indexing

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
102
001/137

QF205
df.iloc[1]  df.iloc[1,:]
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
103
001/137

1
QF205
COMPUTING
2
TECHNOLOGY 3
FOR FINANCE
4

6
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
104
001/137

iloc 1

 row 2

QF205
COMPUTING
TECHNOLOGY  row 3
FOR FINANCE

 row 4

 row 5
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative 6

Finance
Slide
105
001/137
.loc

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
106
001/137

QF205 1
COMPUTING
TECHNOLOGY 2
FOR FINANCE 3
4

6
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
107
001/137

QF205
COMPUTING
TECHNOLOGY 3
FOR FINANCE

 4

5
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative 6
Finance
Slide
108
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
109
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Row-major order

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative https://en.wikipedia.org/wiki/Row-_and_column-major_order
Finance
Slide
110
001/137

https://jakevdp.github.io/PythonDataScien
ceHandbook/02.05-computation-on-arrays-
broadcasting.html

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Stretching and
Dr. Zhao Yibao
Broadcasting
Senior Lecturer
Of Quantitative
(ndarray)
Finance
Slide
111
001/137

Default: float type

QF205 dtype=int  int type


COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide

It seems that
112
001/137

pandas.DataFrame
does not have
ndarray’s
QF205
COMPUTING
TECHNOLOGY
“Stretching and
FOR FINANCE
Q: Why is it 2.0?
A: NaN is float type.
Broadcasting”.

Dr. Zhao Yibao


Senior Lecturer
So what? 😉😉
Of Quantitative
Finance
Slide
113
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Subtraction of Two Series


with different labels.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
114
001/137

QF205 That’s all for today.


COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
115
001/137

𝜏𝜏 = 𝑇𝑇 − 𝑡𝑡

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
(optional)
Finance
Slide For example: 𝑆𝑆 = 50, 𝐾𝐾 = 50, 𝑟𝑟 = 0.04, 𝑞𝑞 = 0.01, 𝜏𝜏 = 183/365, σ = 0.4, and 𝑁𝑁 = 3.
116
001/137
𝜏𝜏 𝜎𝜎 ∆𝑡𝑡 1 𝑒𝑒 𝑟𝑟−𝑞𝑞 ∆𝑡𝑡 −𝑑𝑑
1. ∆𝒕𝒕 = , 𝒖𝒖
= 𝑒𝑒 , 𝒅𝒅 = , 𝒑𝒑 =
𝑁𝑁 𝑢𝑢 𝑢𝑢−𝑑𝑑
2. (𝑖𝑖 = 3)
 (𝑗𝑗 = 0) 𝒇𝒇𝟑𝟑,𝟎𝟎 = max 0, 𝑆𝑆𝑢𝑢0 𝑑𝑑 3−0 − 𝐾𝐾 Call , 𝒇𝒇𝟑𝟑,𝟎𝟎 = max 0, 𝐾𝐾 − 𝑆𝑆𝑢𝑢0 𝑑𝑑 3−0 Put
 (𝑗𝑗 = 1) 𝒇𝒇𝟑𝟑,𝟏𝟏 = max 0, 𝑆𝑆𝑢𝑢1 𝑑𝑑 3−1 − 𝐾𝐾 Call , 𝒇𝒇𝟑𝟑,𝟏𝟏 = max 0, 𝐾𝐾 − 𝑆𝑆𝑢𝑢1 𝑑𝑑 3−1 Put
 (𝑗𝑗 = 2) 𝒇𝒇𝟑𝟑,𝟐𝟐 = max 0, 𝑆𝑆𝑢𝑢2 𝑑𝑑 3−2 − 𝐾𝐾 Call , 𝒇𝒇𝟑𝟑,𝟐𝟐 = max 0, 𝐾𝐾 − 𝑆𝑆𝑢𝑢2 𝑑𝑑 3−2 Put
 (𝑗𝑗 = 3) 𝒇𝒇𝟑𝟑,𝟑𝟑 = max 0, 𝑆𝑆𝑢𝑢3 𝑑𝑑 3−3 − 𝐾𝐾 Call , 𝒇𝒇𝟑𝟑,𝟑𝟑 = max 0, 𝐾𝐾 − 𝑆𝑆𝑢𝑢3 𝑑𝑑 3−3 Put

3.  𝜏𝜏 → tau
 (𝑖𝑖 = 2)
QF205
COMPUTING o (𝑗𝑗 = 0) 𝒇𝒇𝟐𝟐,𝟎𝟎 = 𝑒𝑒 −𝑟𝑟∆𝑡𝑡 [𝑝𝑝 � 𝑓𝑓3,1 + 1 − 𝑝𝑝 � 𝑓𝑓3,0 ]  ∆𝑡𝑡 → deltaT
TECHNOLOGY o (𝑗𝑗 = 1) 𝒇𝒇𝟐𝟐,𝟏𝟏 = 𝑒𝑒 −𝑟𝑟∆𝑡𝑡 [𝑝𝑝 � 𝑓𝑓3,2 + 1 − 𝑝𝑝 � 𝑓𝑓3,1 ]
FOR FINANCE
o (𝑗𝑗 = 2) 𝒇𝒇𝟐𝟐,𝟐𝟐 = 𝑒𝑒 −𝑟𝑟∆𝑡𝑡 [𝑝𝑝 � 𝑓𝑓3,3 + 1 − 𝑝𝑝 � 𝑓𝑓3,2 ]  𝒇𝒇𝒊𝒊,𝒋𝒋 → f[i][j]
 (𝑖𝑖 = 1)
o (𝑗𝑗 = 0) 𝒇𝒇𝟏𝟏,𝟎𝟎 = 𝑒𝑒 −𝑟𝑟∆𝑡𝑡 [𝑝𝑝 � 𝑓𝑓2,1 + 1 − 𝑝𝑝 � 𝑓𝑓2,0 ]
o (𝑗𝑗 = 1) 𝒇𝒇𝟏𝟏,𝟏𝟏 = 𝑒𝑒 −𝑟𝑟∆𝑡𝑡 [𝑝𝑝 � 𝑓𝑓2,2 + 1 − 𝑝𝑝 � 𝑓𝑓2,1 ]
 (𝑖𝑖 = 0)
o (𝑗𝑗 = 0) 𝒇𝒇𝟎𝟎,𝟎𝟎 = 𝑒𝑒 −𝑟𝑟∆𝑡𝑡 [𝑝𝑝 � 𝑓𝑓1,1 + 1 − 𝑝𝑝 � 𝑓𝑓1,0 ]
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
117
001/137

f[0][0]
f[1][0]
f[1][1]
QF205
COMPUTING f[2][0]
TECHNOLOGY
FOR FINANCE f[2][1]
f[2][2]
𝒇𝒇𝒊𝒊,𝒋𝒋 → f[i][j] f[3][0]
f[3][1]
Dr. Zhao Yibao
Senior Lecturer 𝑓𝑓3,0 = 1.1 → f[3][0]=1.1 f[3][2]

Of Quantitative f[3][3]
Finance
Slide
118
001/137
Three Implementations

1. Nested list with for loop


QF205
COMPUTING
2. Nested list with list comprehension
TECHNOLOGY
FOR FINANCE

3. Numpy ndarray

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
119
001/137
Given 𝑁𝑁, …

𝑓𝑓𝑁𝑁,𝑗𝑗 , 𝑗𝑗 = 0, 1, … , 𝑁𝑁 𝑁𝑁 = 3: 𝑓𝑓3,0 , 𝑓𝑓3,1 , 𝑓𝑓3,2 , 𝑓𝑓3,3

𝑓𝑓𝑖𝑖,𝑗𝑗 , 𝑖𝑖 = 𝑁𝑁 − 1, … , 0; 𝑗𝑗 = 0, 1, … , 𝑖𝑖 𝑁𝑁 = 3: 𝑓𝑓2,0 , 𝑓𝑓2,1 , 𝑓𝑓2,2 ; 𝑓𝑓1,0 , 𝑓𝑓1,1 ; 𝑓𝑓0,0

QF205
COMPUTING For example, 𝑁𝑁 = 3
TECHNOLOGY
FOR FINANCE
𝑓𝑓0,0
𝑓𝑓1,0 𝑓𝑓1,1
𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i][j] list, ndarray

𝑓𝑓2,0 𝑓𝑓2,1 𝑓𝑓2,2


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative 𝑓𝑓3,0 𝑓𝑓3,1 𝑓𝑓3,2 𝑓𝑓3,3
𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i,j] ndarray
Finance
Slide
120
001/137

𝑓𝑓0,0 N=3
f=[[0.0 for j in range(0,i+1)]
𝑓𝑓1,0 𝑓𝑓1,1
for i in range(0,N+1)]
𝑓𝑓2,0 𝑓𝑓2,1 𝑓𝑓2,2

QF205
𝑓𝑓3,0 𝑓𝑓3,1 𝑓𝑓3,2 𝑓𝑓3,3
𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i][j] (list)
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
121
001/137

𝑓𝑓0,0 import numpy as np


𝑓𝑓1,0 𝑓𝑓1,1 N=3
f=np.zeros((N+1,N+1))
𝑓𝑓2,0 𝑓𝑓2,1 𝑓𝑓2,2
𝑓𝑓3,0 𝑓𝑓3,1 𝑓𝑓3,2 𝑓𝑓3,3

QF205
COMPUTING
(Numpy ndarray)
TECHNOLOGY
FOR FINANCE
𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i,j]

Dr. Zhao Yibao


𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i][j]
Senior Lecturer
Of Quantitative
Finance
Slide
122
001/137

𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i][j]
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE for j in range(0,N+1):
fc[N][j]=max(0, S*(u**j)*(d**(N-j))-K)
fp[N][j]=max(0, K-S*(u**j)*(d**(N-j)))
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide
123
001/137

𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i][j]
QF205
p1=1-p
COMPUTING ert=math.exp(-r*deltaT)
TECHNOLOGY
FOR FINANCE
for i in range(N-1,0-1,-1):
for j in range(0,i+1):
fc[i][j]=ert*(p*fc[i+1][j+1]+p1*fc[i+1][j])
fp[i][j]=ert*(p*fp[i+1][j+1]+p1*fp[i+1][j])
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide # nested list with for loop
124
001/137 import math

2&3
def V_binomial_tree_py(S,K,r,q,tau,sigma,N=100):
# 1.
deltaT=tau/N
u=math.exp(sigma*math.sqrt(deltaT))
d=1/u
p=(math.exp((r-q)*deltaT)-d)/(u-d)
# 2.
fc=[[0.0 for j in range(0,i+1)] for i in range(0,N+1)]
fp=[[0.0 for j in range(0,i+1)] for i in range(0,N+1)]

for j in range(0,N+1):
fc[N][j]=max(0, S*(u**j)*(d**(N-j))-K)
fp[N][j]=max(0, K-S*(u**j)*(d**(N-j)))
Create fc’s
storage
# 3.
p1=1-p
QF205 ert=math.exp(-r*deltaT)
COMPUTING
TECHNOLOGY for i in range(N-1,0-1,-1):

before using
for j in range(0,i+1):
FOR FINANCE fc[i][j]=ert*(p*fc[i+1][j+1]+p1*fc[i+1][j])
fp[i][j]=ert*(p*fp[i+1][j+1]+p1*fp[i+1][j])
# 4.

fc[i][j].
c=fc[0][0]
p=fp[0][0]
return (c, p)

if __name__=='__main__':
Dr. Zhao Yibao S=50.0; K=50.0; tau=183/365;
sigma=0.4; r=0.04; q=0.01
Senior Lecturer print('Call: {0[0]}, Put: {0[1]}'.format(
Of Quantitative V_binomial_tree_py(S,K,r,q,tau,sigma)))
Finance
Slide # nested list with list comprehension
125
001/137 import math

Create fc’s
def V_binomial_tree_py2(S,K,r,q,tau,sigma,N=100):
# 1.
deltaT=tau/N
u=math.exp(sigma*math.sqrt(deltaT))
d=1/u
p=(math.exp((r-q)*deltaT)-d)/(u-d)
# 2.
storage
before using
fc=[0]*(N+1)
fp=[0]*(N+1)

fc[N]=[max(0, S*(u**j)*(d**(N-j))-K) for j in range(0,N+1)]


fp[N]=[max(0, K-S*(u**j)*(d**(N-j))) for j in range(0,N+1)]

# 3.
fc[i].
p1=1-p
QF205 ert=math.exp(-r*deltaT)
COMPUTING
TECHNOLOGY for i in range(N-1,0-1,-1):
fc[i]=[ert*(p*fc[i+1][j+1]+p1*fc[i+1][j]) for j in range(0,i+1)]
FOR FINANCE fp[i]=[ert*(p*fp[i+1][j+1]+p1*fp[i+1][j]) for j in range(0,i+1)]

# 4.
c=fc[0][0]
p=fp[0][0]
return (c, p)

if __name__=='__main__':
(using list comprehension)
Dr. Zhao Yibao S=50.0; K=50.0; tau=183/365;
sigma=0.4; r=0.04; q=0.01
Senior Lecturer print('Call: {0[0]}, Put: {0[1]}'.format(
Of Quantitative V_binomial_tree_py2(S,K,r,q,tau,sigma)))
Finance
Slide
126
001/137

(ndarray)
(Dr. Z: Remember ndarrays

QF205
𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i,j] allow vectorized operations?
COMPUTING
TECHNOLOGY
FOR FINANCE
for j in range(0,N+1):
fc[N,j]=max(0, S*(u**j)*(d**(N-j))-K)

Dr. Zhao Yibao


fp[N,j]=max(0, K-S*(u**j)*(d**(N-j)))
Senior Lecturer
Of Quantitative
Finance
Slide
127
001/137 for j in range(0,N+1):
fc[N,j]=max(0, S*(u**j)*(d**(N-j))-K)
fp[N,j]=max(0, K-S*(u**j)*(d**(N-j)))

j=np.arange(0,N+1);
QF205
COMPUTING
Ss=S*(u**j)*(d**(N-j))
vectorized
operations
TECHNOLOGY
FOR FINANCE

fc[N,:]=np.maximum(0, Ss-K)
𝑦𝑦 = 2𝑥𝑥1 + 3 𝑦𝑦1 𝑥𝑥1 3
� 1 ⟹ 𝑦𝑦 = 2 𝑥𝑥 +
𝑦𝑦2 = 2𝑥𝑥2 + 4 2 2 4
fp[N,:]=np.maximum(0, K-Ss)
Dr. Zhao Yibao 𝒀𝒀 = 2𝑿𝑿 + 𝒃𝒃
Senior Lecturer
Of Quantitative
Finance
0:N+1
Slide
128
001/137 element-wise

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Slide
129
001/137

𝑓𝑓𝑖𝑖,𝑗𝑗 →f[i,j]
QF205 p1=1-p
COMPUTING
TECHNOLOGY ert=math.exp(-r*deltaT)
FOR FINANCE

for i in range(N-1,0-1,-1):
for j in range(0,i+1):
fc[i,j]=ert*(p*fc[i+1,j+1]+p1*fc[i+1,j])
Dr. Zhao Yibao
Senior Lecturer fp[i,j]=ert*(p*fp[i+1,j+1]+p1*fp[i+1,j])
Of Quantitative
Finance
Slide
130
001/137
for i in range(N-1,0-1,-1):
for j in range(0,i+1):
fc[i,j]=ert*(p*fc[i+1,j+1]+p1*fc[i+1,j])
fp[i,j]=ert*(p*fp[i+1,j+1]+p1*fp[i+1,j])

(using vectorized operations)


QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

for i in range(N-1,0-1,-1):
fc[i,0:i+1]=ert*(p*fc[i+1,0+1:i+1+1]+p1*fc[i+1,0:i+1])
fp[i,0:i+1]=ert*(p*fp[i+1,0+1:i+1+1]+p1*fp[i+1,0:i+1])
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
Slide # Numpy ndarray
131
001/137 import numpy as np

def V_binomial_tree_np(S,K,r,q,tau,sigma,N=100):
# 1.
deltaT=tau/N
u=np.exp(sigma*np.sqrt(deltaT))
d=1/u
p=(np.exp((r-q)*deltaT)-d)/(u-d)
# 2.
fc=np.zeros((N+1,N+1))
fp=np.zeros((N+1,N+1))
j=np.arange(0,N+1,1);
Ss=S*(u**j)*(d**(N-j))
fc[N,:]=np.maximum(0, Ss-K)
fp[N,:]=np.maximum(0, K-Ss)
QF205 # 3.
COMPUTING p1=1-p
ert=np.exp(-r*deltaT)
TECHNOLOGY
for i in range(N-1,0-1,-1):
FOR FINANCE fc[i,0:i+1]=ert*(p*fc[i+1,0+1:i+1+1]+p1*fc[i+1,0:i+1])
fp[i,0:i+1]=ert*(p*fp[i+1,0+1:i+1+1]+p1*fp[i+1,0:i+1])
# 4.
c=fc[0,0]
p=fp[0,0]
return (c, p)

if __name__=='__main__':
Dr. Zhao Yibao S=50.0; K=50.0; tau=183/365;
sigma=0.4; r=0.04; q=0.01
Senior Lecturer print('Call: {0[0]}, Put: {0[1]}'.format(
Of Quantitative V_binomial_tree_np(S,K,r,q,tau,sigma)))
Finance
Slide
132
001/137 Numpy https://docs.scipy.org/doc/numpy/reference/routines.html

 numpy.array
 numpy.arange
 numpy.reshape or numpy.ndarray.reshape
 numpy.isin
 numpy.linspace

QF205  numpy.ones, numpy.zeros, numpy.empty


COMPUTING
TECHNOLOGY  numpy.exp, numpy.sqrt
FOR FINANCE
 numpy.mean, numpy.std, numpy.sum, numpy.cumsum
 numpy.maximum
 numpy.random
 numpy.append, numpy.concatenate
Next!
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
 ...(numpy.linalg)...
Finance
Slide
133
002/137

𝜏𝜏 = 𝑇𝑇 − 𝑡𝑡

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

mean
Dr. Zhao Yibao
Senior Lecturer
4 Of Quantitative
Finance
Slide 𝜏𝜏 𝜏𝜏
134
001/137

2
import numpy as np
def V_MonteCharloSimulation(S,K,r,q,tau,sigma,z):
# 2.
QF205 ST=S*np.exp((r-q-0.5*sigma**2)*tau \
COMPUTING
TECHNOLOGY +sigma*np.sqrt(tau)*z)
FOR FINANCE

(Dr. Z: It is compatible to vectorized operations.)


Dr. Zhao Yibao vector z  vector ST
Senior Lecturer
Of Quantitative
Finance
Slide
# Monte Carlo Simulation Option Pricing
135
002/137
import numpy as np
def V_MonteCharloSimulation(S,K,r,q,tau,sigma,z):
# 2.
ST=S*np.exp((r-q-0.5*sigma**2)*tau+sigma*np.sqrt(tau)*z) 2
# 3.
hTc=np.maximum(ST-K,0)
hTp=np.maximum(K-ST,0) 3
# 4.
c=np.exp(-r*tau)*np.mean(hTc)
p=np.exp(-r*tau)*np.mean(hTp) 4
return (c, p)
QF205
COMPUTING
if __name__=='__main__': TECHNOLOGY
S=50.0; K=50.0; tau=183/365 FOR FINANCE
sigma=0.4; r=0.04; q=0.01
# 1.
N=10_000_000
np.random.seed(0)
z=np.random.standard_normal(N)
z=np.append(z, -z) #variance reduction by antithetic variates
1 Dr. Zhao Yibao
print('Call: {0[0]}, Put: {0[1]}'.format( Senior Lecturer
V_MonteCharloSimulation(S,K,r,q,tau,sigma,z))) Of Quantitative
Finance
Slide
136
001/137

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative (See “Summary of
Finance Applications in QF205.pdf”.)
Slide
137
001/137
 HDB Loan

Next!
 IRAS Income Tax
 Pandigital Formula
 Sudoku Solver

Option Pricing:

Excel!
QF205
COMPUTING
TECHNOLOGY

 Black-Scholes Formula
FOR FINANCE

 Binomial Tree Method


 Monte Carlo Simulation
Method
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance

You might also like