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

SMU Classification: Restricted

Slide
001
001/149
QF205 - Computing Technology For Finance
Week 04

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Preparations
Dr. Zhao Yibao Get your laptop ready.
Senior Lecturer
Of Quantitative
Launch Jupyter notebook and open “QF205 Notebook WK04.ipynb”.
Finance
SMU Classification: Restricted
Slide 2
002
001/149
Quick Review of Week 03

q We defined a simple function (funP) with docstring


q We created a simple module (myQF205Lib.py) with docstring
QF205
COMPUTING q We explored the package structure (foo scenario 1)
TECHNOLOGY
FOR FINANCE
q How import works
q Use of built-in functions: dir()
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
003
001/149
Today, we’re going to learn
String operations
Lists and list operations
Tuples and tuple operations
QF205 Membership test operations
COMPUTING
TECHNOLOGY
FOR FINANCE
Boolean operations
Comparisons
The if statement
Dr. Zhao Yibao
Senior Lecturer
Built-in functions (enumerate(), map(), filter(), next())
Of Quantitative
Finance
SMU Classification: Restricted
Slide
004
001/149

QF205
COMPUTING
TECHNOLOGY
String Operations
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
005
001/149

Strings can be concatenated (glued


together) with the + operator, and

repeated with *.
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
006
001/149

Two or more string literals (i.e. the ones enclosed


between quotes) next to each other are automatically

concatenated. This only works with two literals


though, not with variables or expressions.

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
007
002/149

Error: with variables QF205


COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Error: with expressions Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide

Q: What will be shown in Out[5]? 008


002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
[Hint: “implicit line joining” and “string concatenation”] Of Quantitative
Finance
SMU Classification: Restricted
Slide
009
001/149

String indexed s can be (subscripted), with the

first index 0. no
character having There is separate

QF205
COMPUTING
TECHNOLOGY
character type; a character is
FOR FINANCE
simply a string of size one.
(An example is on next slide.)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
010
002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

0 1 2 3 4 5

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
011
001/149

Indices may also be negative


QF205
numbers, to start
COMPUTING
TECHNOLOGY
FOR FINANCE counting from the right.
(An example is on next slide.)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
012
002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

-6 -5 -4 -3 -2 -1

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
013
002/149
String Indexing

QF205
COMPUTING
0 1 2 3 4 5 TECHNOLOGY
FOR FINANCE

-6 -5 -4 -3 -2 -1

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
014
002/149

IndexError: string index out of range

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
015
001/149

slicing is also supported. While


In addition to indexing,

indexing is used to obtain


QF205
COMPUTING
TECHNOLOGY
individual characters, slicing
FOR FINANCE
allows you to obtain substring.
(An example is on next slide.)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
016
002/149

a:b
means from position a QF205
COMPUTING
(included) to position b TECHNOLOGY
FOR FINANCE
(excluded), from left to right.

0 1 2

Dr. Zhao Yibao


2 3 4 5 Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
017
002/149

QF205
COMPUTING
(indices) TECHNOLOGY
FOR FINANCE

(slices)
(extended slices)
Dr. Zhao Yibao
Senior Lecturer
https://docs.python.org/3/library/stdtypes.html#common-sequence-operations Of Quantitative
Finance
SMU Classification: Restricted
Slide
018
001/149

0 1 2 3 4 5

-6 -5 -4 -3 -2 -1

word[0:2]
QF205
COMPUTING
TECHNOLOGY
from 0 to 2
FOR FINANCE
=word[0]+word[1]
word[2:5]
from 2 to 5
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
=word[2]+word[3]+word[4]
Finance
SMU Classification: Restricted
Slide
019
001/149

0 1 2 3 4 5

-6 -5 -4 -3 -2 -1

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
? word[-5:5]
? from -5 to 5
i.e. word[-5]+word[-4]+word[-3]+word[-2]+word[-1]+word[0]+word[1]
+word[2]+word[3]+word[4]

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
NO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Finance
SMU Classification: Restricted
Slide
020
001/149

0 1 2 3 4 5
a 6-letter word -6 -5 -4 -3 -2 -1

word[-5:5]
QF205
COMPUTING original: from -5 to 5 +6
TECHNOLOGY
FOR FINANCE
Stage 1: from 1 to 5
Stage 2: from 1 to 5
Dr. Zhao Yibao
Senior Lecturer =word[1]+word[2]+word[3]+word[4]
Of Quantitative
Finance
SMU Classification: Restricted
Slide
021
001/149

0 1 2 3 4 5
a 6-letter word -6 -5 -4 -3 -2 -1

word[-8:7]
QF205
COMPUTING original: from -8 to 7 +6
TECHNOLOGY
FOR FINANCE
Stage 1: from -2 to 7 -2 0, 7 6
Stage 2: from 0 to 6
Dr. Zhao Yibao =word[0]+word[1]+word[2]+word[3]+word[4]+word[5]
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
022
001/149
Stage 1: negative i or j plus length
(omitted omitted)

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE If i or j is negative, the index is relative to the end of

sequence s: len(s)+i len(s)+j or is


substituted. But note that -0 is still 0.

Dr. Zhao Yibao i* = i, if i>=0 j* = j, if j>=0


Senior Lecturer = i+len(s), if i<0 = j+len(s), if j<0
Of Quantitative
Finance
SMU Classification: Restricted
Slide
023
001/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
len()
Of Quantitative
Finance
SMU Classification: Restricted
Slide
024
001/149
Stage 2

slice of s from i* to j* is defined as the


The

sequence of items with index m


QF205
COMPUTING
such that i*<=m<j*.
TECHNOLOGY
FOR FINANCE
If i* or j* is greater than len(s), use len(s).
If i* or j* is less than 0, use 0.
If i* is omitted or None, use 0. (default values)
If j* is omitted or None, use len(s).
Dr. Zhao Yibao Slide 28 If i* is greater than or equal to j*, the
Senior Lecturer
Of Quantitative
Finance
slice is empty.
SMU Classification: Restricted
Slide
025
001/149
Stage 2
(extended slices)

Extended Slices (1/2):


When k is positive, i* and j* are reduced to
len(s) if they are greater (than len(s)); 0 if
QF205 they are less (than 0).
COMPUTING
TECHNOLOGY When k is negative, i* and j* are reduced to
FOR FINANCE
len(s)-1 if they are greater (than len(s)-1); -1
if they are less (than -1).
If i* or j* are omitted or None, they become
Slide 30 “end” values (which end depends on the sign of
Dr. Zhao Yibao
Senior Lecturer k). Note, k cannot be zero. (end value in a subsequent slide)
Of Quantitative
Finance
If k is None, it is treated like 1.
SMU Classification: Restricted
Slide
026
001/149
Stage 2
(extended slices)

Extended Slices (2/2): The slice of s from


i* to j* with step k is defined as the sequence
QF205
COMPUTING
of items with index x=i*+n*k such that
TECHNOLOGY
FOR FINANCE 0<=n<(j*-i*)/k. In other words, the indices are i*,
i*+k, i*+2*k, i*+3*k and so on,
stopping when j* is reached (but never
Dr. Zhao Yibao
including j*).
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
027
002/149
Q: What is the output?

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

o) from -5 to 5
1) from 1 to 5
2) from 1 to 5 Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
028
001/149
Q: What is the output?

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

o) from 5 to 2
1) from 5 to 2
Dr. Zhao Yibao
2) from 5 to 2
Senior Lecturer
Of Quantitative
<empty string>
Finance
SMU Classification: Restricted
Slide
029
002/149

o) from -8 to -7
1) from -2 to -1
2) from 0 to 0 empty
o) from 7 to 8 QF205
COMPUTING
1) from 7 to 8 TECHNOLOGY
FOR FINANCE
2) from 6 to 6 empty
<empty string>
<empty string> o) from -8 to 7
1) from -2 to 7 Dr. Zhao Yibao
2) from 0 to 6 Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
030
001/149
“end”
values
Extended slice indices have useful defaults:
if k>0, an omitted first index i* defaults
QF205
COMPUTING
to 0, an omitted second index j* defaults
TECHNOLOGY
FOR FINANCE to len(s).
if k<0, an omitted first index i* defaults
to len(s)-1, an omitted second index
Dr. Zhao Yibao
j* defaults to -1.
Senior Lecturer Slide 25
Of Quantitative
Finance
SMU Classification: Restricted
Slide
031
001/149

o) from omitted to 2
1) from omitted to 2
2) from 0 to 2
QF205
COMPUTING
o) from 4 to omitted
TECHNOLOGY
FOR FINANCE 1) from 4 to omitted
2) from 4 to 6
o) from -2 to omitted
Dr. Zhao Yibao 1) from 4 to omitted
Senior Lecturer
Of Quantitative 2) from 4 to 6
Finance
SMU Classification: Restricted
Slide
032
001/149 o) from omitted to omitted with step 3
1) from omitted to omitted with step 3
2) from 0 to 10 with step 3
=word[0]+word[3]+word[6]+word[9]

o) from omitted to omitted with step -3


1) from omitted to omitted with step -3
2) from 9 to -1 with step -3
=word[9]+word[6]+word[3]+word[0]
QF205
COMPUTING o) from -2 to 2 with step -1
TECHNOLOGY
FOR FINANCE 1) from 8 to 2 with step -1
2) from 8 to 2 with step -1
=word[8]+word[7]+word[6]+word[5]+word[4]
+word[3]

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
033
002/149

o) from 2 to omitted with step 2


1) from 2 to omitted with step 2
2) from 2 to 10 with step 2
=word[2]+word[4]+word[6]+word[8]

o) from -2 to omitted with step -2 QF205


1) from 8 to omitted with step -2 COMPUTING
TECHNOLOGY
2) from 8 to -1 with step -2 FOR FINANCE
=word[8]+word[6]+word[4]+word[2]+word[0]

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
034
001/149

Pythonstrings cannot be changed — they


are immutable. Therefore, assigning to an
QF205
COMPUTING
TECHNOLOGY
indexed position in the string
FOR FINANCE
results in an error.
(see example on next slide)
https://docs.python.org/3/tutorial/introduction.html#strings
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
035
001/149

TypeError
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative slide 44
Finance
SMU Classification: Restricted
Slide
036
002/149
Examples:
Commonly used string operations in Python:
Prepend, insert and append
word = '---' + word
word = word[:2] + '---' + word[2:] QF205
COMPUTING
word = word + '---' TECHNOLOGY
FOR FINANCE
Delete
word = word[:2] + word[4:]
Replace
Dr. Zhao Yibao
word = word[:2] + '---' + word[4:] Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
037
002/149

y 'Python'
word

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
y 'Python'
word '---Python'

SAME ID Dr. Zhao Yibao


Senior Lecturer
DIFFERENT IDs
Of Quantitative
Finance
SMU Classification: Restricted
Slide
038
002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

In this example, the IDs


of y and word have no Dr. Zhao Yibao

changes. (Why?) Senior Lecturer


Of Quantitative
Finance
SMU Classification: Restricted
Slide
String Methods https://docs.python.org/3/library/stdtypes.html#string-methods
039
002/149

.upper(), .lower()
.count() Q: Do you still
.find(), .rfind() remember
.replace() these two??
.split(), .rsplit() QF205
COMPUTING
.format() TECHNOLOGY
FOR FINANCE

.index(), .rindex() Before showing


.strip(), .rstrip() examples, let’s
.title() first learn what Dr. Zhao Yibao
.zfill() Do Not Test a list is. Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
040
001/149

Lists and List


QF205
COMPUTING
TECHNOLOGY
Operations
FOR FINANCE
https://docs.python.org/3/library/stdtypes.html#lists
https://docs.python.org/3/tutorial/introduction.html#lists
https://docs.python.org/3/tutorial/datastructures.html
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
041
001/149

Python knows a number of compound data types,


used to group together other values. The most versatile is the

QF205
list, which can be written as a list of comma-separated
COMPUTING
TECHNOLOGY values (items) between square
FOR FINANCE
brackets. Lists might contain items of different types, but usually the
items all have the same type.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
042
001/149

Like strings (and all other


built-in sequence type), lists
QF205
can be indexed and sliced.
All slice operations return a
COMPUTING
TECHNOLOGY
FOR FINANCE

new list containing the


requested elements.
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
043
002/149

1 4 9 16 25

0 1 2 3 4

-5 -4 -3 -2 -1

from 2 to 5 with step 1: 2, 3, 4


from 0 to 3 with step 1 : 0, 1, 2
QF205
from 0 to 5 with step 2 : 0, 2, 4 COMPUTING
from 4 to -1 with step -2 : 4, 2, 0 TECHNOLOGY
FOR FINANCE

indexing an item

slicing list Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
044
001/149
Strings are immutable.
slide 35

Lists mutable sequences


are ,
typically used to store collections of homogeneous items (where the
precise degree of similarity will vary by application).
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
NO error.
Finance
SMU Classification: Restricted
Slide
045
001/149

In this example, both y and squares


are bound to the same list object!!!
What if I need a copy?

1 squares y

2
QF205
COMPUTING 3 (a list object) 1 (an int object)
TECHNOLOGY
FOR FINANCE
1 SAME ID [0] 4 (an int object)
2 [1]
3 SAME ID 9 (an int object)
[2]
[3] 16 (an int object)
Dr. Z: For simplicity, we can treat
Dr. Zhao Yibao [4]
Senior Lecturer squares[0]/y[0], squares[1]/y[1], …, 25 (an int object)
Of Quantitative squares[4]/y[4] as names/identifiers.
Finance
SMU Classification: Restricted
Slide
046
001/149

QF205
Shallow copy of lists
COMPUTING
TECHNOLOGY
FOR FINANCE
Deep copy of lists
http://www.python-course.eu/python3_deep_copy.php

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
047
001/149

squares y

1
1
[0] [0]
2 4
[1] [1]
QF205 3
COMPUTING [2] 9 [2]
TECHNOLOGY
FOR FINANCE 1 DIFFERENT IDs [3] [3]
16
2
3 NO CHANGE in IDs
[4] [4]
25

[:]
Slicing creates a
Dr. Zhao Yibao
Senior Lecturer
new list, known
Of Quantitative
Finance
as a shallow copy.
SMU Classification: Restricted
Slide
048
001/149
Nested Lists (lists containing other lists)
lst1=['a','b',['ab','ba']]

[0] 'a'
QF205
COMPUTING
TECHNOLOGY lst1 [1] 'b'
FOR FINANCE [0] 'ab'
[2]
[1] 'ba'

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
What is a shallow copy of lst1?
Finance
SMU Classification: Restricted
Slide

lst2=lst1[:] (shallow copy) 049


002/149

lst1 lst2

[0] 'a' [0]


[1] 'b' [1]
QF205
[2] [2] COMPUTING
TECHNOLOGY
[0] 'ab' FOR FINANCE

[1] 'ba'

What will happen if we proceed with


? lst2[0]='c' Dr. Zhao Yibao
Senior Lecturer
? lst2[2][1]='d' Of Quantitative
Finance
SMU Classification: Restricted
Slide
Shallow Deep http://www.python-course.eu/python3_deep_copy.php
050
002/149

(It is essential when we have a nested list, i.e. list in list.)

lst1=['a','b',['ab','ba']] # Q: len(lst1)=?
lst2=lst1[:] # a shallow copy
lst2[0]='c'
'c'
print(lst1, lst2)
'a' QF205
COMPUTING
lst2[2][1]='d' lst1 'b' lst2
TECHNOLOGY
FOR FINANCE
print(lst1, lst2)

(Output is on 'ab'

Dr. Zhao Yibao


the next slide.) 'd' 'ba'
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
051
002/149

2
1 QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Z: The shallow copy of a


nested list only creates a
new list for the outermost Dr. Zhao Yibao
Senior Lecturer
level, inner lists are shared. 2 Of Quantitative
Finance
SMU Classification: Restricted
Slide
052
001/149
Shallow Deep http://www.python-course.eu/python3_deep_copy.php

(Use deep copy when we need a complete copy of a nested list.)


from copy import deepcopy
lst1=['a','b',['ab','ba']]
lst2=deepcopy(lst1) # This is a deep copy

QF205 'a'
COMPUTING
TECHNOLOGY lst1 'b' lst2
FOR FINANCE

'ab'

'ba'
What will happen if we proceed with
Dr. Zhao Yibao ? lst2[0]='c'
Senior Lecturer
Of Quantitative ? lst2[2][1]='d'
Finance
SMU Classification: Restricted
Slide
(continued) 053
002/149

from copy import deepcopy


lst1=['a','b',['ab','ba']]
lst2=deepcopy(lst1) # a deep copy
lst2[0]='c'
print(lst1, lst2)
'c'

lst2[2][1]='d' 'a'
QF205
COMPUTING
print(lst1, lst2) lst1 'b' lst2
TECHNOLOGY
FOR FINANCE

(Output is on 'ab'

'ba'

the next slide.) 'd'


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
054
002/149

2
1
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

This example demonstrates


how deepcopy works on a
level-2 nested list. How about
higher level of nested lists? Dr. Zhao Yibao
Senior Lecturer
2 Of Quantitative
Finance
SMU Classification: Restricted
Slide
055
002/149
Lists also support operations like concatenation.

Q: What if we want the “+” to


QF205
compute the elementwise sum, COMPUTING
TECHNOLOGY
i.e. the sum of two vectors? FOR FINANCE

(See next slide.)


Q: What is the output if we run
squares*2? Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
056
001/149

elementwise sum
1
2
QF205 3
COMPUTING
4
TECHNOLOGY
FOR FINANCE

4 solutions are shown here.


No hurry! We’ll learn all of
Dr. Zhao Yibao
Senior Lecturer
them in subsequent lectures.
Of Quantitative
Finance
SMU Classification: Restricted
Slide
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists Do Not Test 057
002/149

Below are ALL of the methods of list objects:


1. list.append(x) Add an item (x) to the end of the list.

2. list.extend(iterable) Extend the list by appending all the items from the iterable.

3. list.insert(i,x) Insert an item (x) at a given position (i).

4. list.remove(x) Remove the first item from the list whose value is x.

5. list.pop([i]) Remove the item at the given position (i) or the last item in the list, and return it. QF205
COMPUTING
6. list.clear() Remove all items from the list TECHNOLOGY
FOR FINANCE
7. list.index(x[, start[,end]]) Return zero-based index in the list of the first item whose value is x.

8. list.count(x) Return the number of times x appears in the list.

9. list.sort(key=None, reverse=False) Sort the items of the list in place


10.list.reverse() Reverse the elements of the list in place.
Dr. Zhao Yibao
11.list.copy() A shallow copy of the list. Senior Lecturer
Of Quantitative
[ . ]: represents an optional argument Finance
SMU Classification: Restricted
Slide
058
002/149

list.append(x)
list.extend(x)
list.pop() QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
list.pop(i)

Same ID indicates that the Dr. Zhao Yibao


above are in-place operations. Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
059
002/149

(type constructor)

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

2:5
Assignment to slices is also
2:5
possible, and this can even
change the size of the list Dr. Zhao Yibao

or clear it entirely. Senior Lecturer


Of Quantitative
Finance
SMU Classification: Restricted
Slide
060
002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
061
001/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
062
002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

1
2
Dr. Zhao Yibao
1 Senior Lecturer
2 Of Quantitative
Finance
SMU Classification: Restricted
Slide
063
002/149
(continued)
t[0] 'First $20,000 Next $10,000'

method chaining/cascading
1
2 QF205
3 COMPUTING
4 TECHNOLOGY
FOR FINANCE
5

1
2 .split()
3
4
5
.replace('$', '')
Dr. Zhao Yibao
.replace(',', '') Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
064
001/149

str.replace(old, new[, count])


Return a copy of the string with all occurrences of
QF205 substring old replaced by new. If the optional argument
COMPUTING
TECHNOLOGY
FOR FINANCE
count is given, only the first count
occurrences are replaced.
https://docs.python.org/3/library/stdtypes.html#str.replace

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
065
001/149

str.split(sep=None, maxsplit=-1) (1/6)

Return a list of the words in the string, using sep as


QF205 the delimiter string. If maxsplit is given, at most
COMPUTING
TECHNOLOGY
FOR FINANCE maxsplit splits are done.
https://docs.python.org/3/library/stdtypes.html#str.split
(see In-Class Exercise 31)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
066
001/149

str.split(sep=None, maxsplit=-1) (2/6)

If sep is given, consecutive delimiters are not


QF205 grouped together and are deemed to delimit
COMPUTING
TECHNOLOGY empty strings (for example, '1,,2'.split(',')
FOR FINANCE
returns ['1', '', '2']).
https://docs.python.org/3/library/stdtypes.html#str.split
(see In-Class Exercise 31)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
067
001/149

str.split(sep=None, maxsplit=-1) (3/6)

If sep is given … The sep argument


QF205
may consist of multiple characters (for
COMPUTING
TECHNOLOGY
FOR FINANCE
example, '1<>2<>3'.split('<>') returns
['1', '2', '3']).
https://docs.python.org/3/library/stdtypes.html#str.split
(see In-Class Exercise 31)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
068
001/149

str.split(sep=None, maxsplit=-1) (4/6)

If sep is given … Splitting an


QF205
COMPUTING
TECHNOLOGY
empty string with a specified
FOR FINANCE
separator ['']. returns

https://docs.python.org/3/library/stdtypes.html#str.split
(see In-Class Exercise 31)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
069
001/149

str.split(sep=None, maxsplit=-1) (5/6)

If sep is not specified or is None, a different splitting


algorithm is applied: runs of consecutive whitespace are
QF205
COMPUTING regarded as a single separator, and the result will
TECHNOLOGY
FOR FINANCE contain no empty strings at the start or end if
the string has leading or trailing whitespace.
https://docs.python.org/3/library/stdtypes.html#str.split
(see In-Class Exercise 31)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
070
001/149

str.split(sep=None, maxsplit=-1) (6/6)

Consequently, splitting an empty string or a string


QF205 consisting of just whitespace with a None
COMPUTING
TECHNOLOGY
FOR FINANCE separator returns [].
https://docs.python.org/3/library/stdtypes.html#str.split
(see In-Class Exercise 31)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
071
001/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
072
001/149

QF205
Tuples
COMPUTING
TECHNOLOGY
FOR FINANCE https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range
https://docs.python.org/3/library/stdtypes.html#tuple

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
073
001/149

Tuples are immutable


sequences, typically used to store collections of
heterogeneous data (such as the 2-tuples produced by the enumerate() built-
in). Tuples are also used for cases where an immutable sequence of
homogeneous data is needed (such as allowing storage in a set or dict instance).

QF205
COMPUTING
TECHNOLOGY
x=(1, 2, 3, [4, 5])
FOR FINANCE A tuple object 1
[0] 2
x [1] A list object An int object
3 4
[2] [0] Rebinding is NOT allowed.
[3] [1] 5
Dr. Zhao Yibao
Senior Lecturer Rebinding is allowed.
Of Quantitative (fixed size) (changeable size)
Finance
SMU Classification: Restricted
Slide
074
001/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
Here, we see “iterable” again.
SMU Classification: Restricted
Slide
075
001/149

Note that it is actually the comma which makes a


tuple, not the parentheses. The
parentheses are optional, except in the
empty tuple case, or when they are
QF205
COMPUTING
TECHNOLOGY
needed to avoid syntactic ambiguity. For
example, f(a, b, c) is a function call with three
FOR FINANCE

arguments, while f((a, b, c)) is a function call


with a 3-tuple as the sole argument.
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
common-sequence-operations
https://docs.python.org/3/library/stdtypes.html# 076
002/149

We have seen these QF205

operations
COMPUTING
TECHNOLOGY
FOR FINANCE

and these.
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
common-sequence-operations
https://docs.python.org/3/library/stdtypes.html# 077
002/149

Next, we explore these


QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

and these (next week).


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
078
001/149

Membership Test
Operations
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

https://docs.python.org/3/reference/expressions.html#membership-test-operations

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
079
001/149

operators in not
The and

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
in test for membership.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
080
001/149

x in s evaluates to True if x is
a member of s, and False
QF205
COMPUTING
TECHNOLOGY
otherwise.
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative (Dr. Z: Lists such as [1, 2, 3] and [[1],[2],[3]] are known as containers.)
Finance
SMU Classification: Restricted
Slide
081
001/149

All built-in sequences and set


types support this (membership
QF205
test) as well as dictionary, for
COMPUTING
TECHNOLOGY
FOR FINANCE
which in tests whether the
dictionary has a given key.
(We’ll explore set and dictionary later.)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
082
001/149

For the string , x in y


and bytes types is

QF205
COMPUTING
True if and only if x is a substring
TECHNOLOGY
FOR FINANCE
of y.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
083
001/149

Empty strings are always


considered to be a
QF205
COMPUTING
substring of any other
TECHNOLOGY
FOR FINANCE string, '' in 'abc' so will

return True.
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
084
001/149

For user-defined classes, membership


test depends on the implementation of
QF205 the __contains__() method, the
COMPUTING
TECHNOLOGY __iter__() method, or the
FOR FINANCE
__getitem__() method.

(Dr. Z: We’ll explore this in another lesson.)


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
085
001/149

x not in s

not x in s

QF205
COMPUTING
not (x in s)
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
086
001/149

Boolean Operations
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE and, or, not
https://docs.python.org/3.6/library/stdtypes.html#boolean-operations-and-or-not

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
087
002/149

3
higher
2 priority

QF205
1 COMPUTING
TECHNOLOGY
FOR FINANCE

x or not y and z x or ((not y) and z)


3 1 2
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
088
001/149

Truth Table (1)


x y x and y x or y
True True True True
QF205
True False False True
COMPUTING
TECHNOLOGY False True False True
FOR FINANCE not evaluated
False False False False

and only evaluates the second


is a short-circuit operator, so it

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
argument if the first one is True.
Finance
SMU Classification: Restricted
Slide
089
001/149

Truth Table (2)


x y x and y x or y
True True True True
not evaluated
QF205
True False False True
COMPUTING
TECHNOLOGY False True False True
FOR FINANCE
False False False False

or only evaluates the second


is a short-circuit operator, so it

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
argument if the first one is False.
Finance
SMU Classification: Restricted
Slide
090
001/149

not has a lower priority than


non-Boolean operators, so
not a == b
QF205 is interpreted as
COMPUTING
TECHNOLOGY
FOR FINANCE
not (a == b),
and a == not b is a syntax error.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
a == (not b)
Finance
SMU Classification: Restricted
Slide
091
002/149

same

QF205

SyntaxError COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
092
002/149

List: []
Tuple: ()
1
2 Mixed Types
3

4 QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

1 in, not in
2
3
0 1 2
Why “False”?
Dr. Zhao Yibao
4 Senior Lecturer
0 1 2 Of Quantitative
Finance
SMU Classification: Restricted
Slide
093
002/149

empty list
empty tuple
1
2
3

4 QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

1
2
in, not in
3

4
empty Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
094
002/149

one-element list
This is not a tuple.
one-element tuple, or one-tuple
one-element tuple, or one-tuple
1
2 QF205
COMPUTING
3 TECHNOLOGY
4 It is actually the FOR FINANCE

1
2
comma which
3 makes a tuple, not Dr. Zhao Yibao

4 the parentheses. Senior Lecturer


Of Quantitative
Finance
SMU Classification: Restricted
Slide
095
001/149

QF205
COMPUTING
Iterables
TECHNOLOGY
FOR FINANCE (Source: http://nvie.com/posts/iterators-vs-generators/)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
Iterables Strings 096
002/149

Lists
Tuples
Sets
Dictionaries
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

HERE!
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
(Source: http://nvie.com/posts/iterators-vs-generators/) Finance
SMU Classification: Restricted
Slide
097
002/149

Strings

1
2
QF205
3 tuple() COMPUTING
Lists Tuples TECHNOLOGY
FOR FINANCE
1 list()
2
3

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
isinstance() https://docs.python.org/3/library/functions.html#isinstance 098
002/149

isinstance(object, classinfo)

Return true if the object


argument is an instance of the
classinfo argument, or of a
(direct, indirect or virtual) QF205
subclass thereof. If object is COMPUTING
not an object of the given type, TECHNOLOGY
FOR FINANCE
the function always returns false.
If classinfo is a tuple of type
objects (or recursively, other such
tuples), return true if object is
an instance of any of the types. If
classinfo is not a type or Dr. Zhao Yibao
tuple of types and such tuples, a Senior Lecturer
TypeError exception is raised. Of Quantitative
Finance
SMU Classification: Restricted

https://docs.python.org/3/library/datatypes.html Slide
099
002/149
https://docs.python.org/3/library/collections.abc.html

Abstract Base Classes

QF205
COMPUTING

isinstance() TECHNOLOGY
FOR FINANCE
side 149

An object/class with the __iter__ method implemented


is considered as an abc.Iterable object.
An object/class with the __contains__ method
Dr. Zhao Yibao
implemented is considered as an abc.Container object. Senior Lecturer
Of Quantitative
(Dr. Z: We’ll explore this in another lesson.) Finance
SMU Classification: Restricted
Slide
100
001/149

enumerate()
QF205
COMPUTING https://docs.python.org/3/library/functions.html#enumerate
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
101
001/149
enumerate(iterable, start=0)

Return an enumerate object ,

which is an iterator.
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
102
001/149

enumerate(iterable, start=0)

The __next__() method of the


iterator returned by enumerate()
returns a tuple containing a count
QF205
COMPUTING
TECHNOLOGY
(from start which defaults to 0) and
FOR FINANCE
the values obtained from iterating over
iterable.

x._ _ next_ _ () next(x)


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
103
002/149
enumerate(iterable, start=0)

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Remember we can use list()


on an iterable to create a list? Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
104
002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
105
001/149

lambda expressions
QF205
COMPUTING
TECHNOLOGY https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions
FOR FINANCE
https://docs.python.org/3/reference/expressions.html#lambda

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
106
001/149

QF205
lambda is a Python keyword.
COMPUTING
TECHNOLOGY
FOR FINANCE
(see Week 02 notes)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
107
001/149

lambda expressions (sometimes called lambda forms) are


used to create anonymous functions. The expression
lambda arguments: expression
yields a function object. The unnamed object behaves like a
function object defined with:

QF205 def <lambda>(arguments):


COMPUTING
TECHNOLOGY return expression
FOR FINANCE

Note that functions created with lambda


expressions cannot contain statements or
annotations.
Dr. Zhao Yibao
Senior Lecturer (see example on the next slide)
Of Quantitative
Finance
SMU Classification: Restricted
Slide
108
002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

lambda x: x-1
lambda x: x[1]-1 anonymous Dr. Zhao Yibao
Senior Lecturer
lambda x,y: x+y Of Quantitative
Finance
SMU Classification: Restricted
Slide
109
001/149

filter(), map()
QF205
COMPUTING
TECHNOLOGY
https://docs.python.org/3/library/functions.html#filter
FOR FINANCE
https://docs.python.org/3/library/functions.html#map

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
110
002/149

QF205
COMPUTING

…(function, iterable) TECHNOLOGY


FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
111
002/149

a function object with name f


a function object with name g
1
2
3

4 QF205
COMPUTING
TECHNOLOGY
1 f(2)=2*2=4, g(1,2)=1+2=3 FOR FINANCE
2 element-wise square using map()
3 element-wise summation using map() lambda
4 using filter()
map
?? 1 True, 0 False ?? filter Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
112
001/149

next()
QF205
COMPUTING
TECHNOLOGY https://docs.python.org/3/library/functions.html#next
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
113
001/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

(See example on the next slide.)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
114
002/149
enumerate() returns
an iterator, remember?
next(iterator, default)

QF205
default is returned COMPUTING
TECHNOLOGY
when iterator is exhausted. FOR FINANCE

raise StopIteration Error

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
115
001/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
Discussion:
What do these 2 lines of
(2, 5) ?? code do? Is it possible to
Dr. Zhao Yibao (Dr. Z: The answer will be given show the position of the
Senior Lecturer
Of Quantitative today in another in-class exercise.) number 5 too, e.g. (2, 5)?
Finance
SMU Classification: Restricted
Slide
116
001/149

Truth Value Testing


QF205
COMPUTING
TECHNOLOGY https://docs.python.org/3/library/stdtypes.html#truth-value-testing
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
117
001/149

Any object can be


QF205
COMPUTING
tested for truth value ,
TECHNOLOGY
FOR FINANCE for use in an if or while condition or
as operand of the Boolean operations.

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
118
001/149

Here are most of the built-in objects considered false:


None
False
QF205
COMPUTING
Zeroes: 0, 0.0, 0j, …
TECHNOLOGY
FOR FINANCE
Empty sequences and
collections: '', (), [],
set(), range(0)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
119
001/149

bool()
QF205
COMPUTING
TECHNOLOGY
https://docs.python.org/3/library/functions.html#bool
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
120
001/149

class bool([x])

Return a Boolean value, i.e. one


of True or False. x is converted using the
standard truth testing procedure. If x is false or omitted, this
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
returns False; otherwise it returns True. The bool
class is a subclass of int (see Numeric Types — int, float, complex). It cannot
be subclassed further. Its only instances are False and True (see Boolean
Values).

(see example on the next slide)


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
x omitted 121
002/149

None

False

Zero
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Empty Sequences and Collections

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
122
001/149

Comparisons
QF205
COMPUTING https://docs.python.org/3.6/library/stdtypes.html#comparisons
TECHNOLOGY
FOR FINANCE https://docs.python.org/3/reference/expressions.html#comparisons

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
123
001/149

eight comparison
There are

QF205
COMPUTING
operations in Python .

same priority
TECHNOLOGY
FOR FINANCE
They all have the (which is
higher than that of the Boolean operations).

1 2 3 4 5 6 7 8
Dr. Zhao Yibao < <= > >= == != is is not
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
124
001/149
Comparisons can be chained arbitrarily; for example,
x<y<=z is equivalent to x<y and y<=z,
except that y is evaluated only once (but
in both cases z is not evaluated at all
when x<y is found to be false).
QF205
COMPUTING
Dr. Z: I remember! and is a short-circuit operator.
TECHNOLOGY
FOR FINANCE

1<2<=3 1<2 and 2<=3


1<2>=3<4 1<2 and 2>=3 and 3<4
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
(See in-class exercise 43.)
Finance
SMU Classification: Restricted
Slide
125
001/149

value comparison
2 order
3 comparison
QF205 4
COMPUTING
TECHNOLOGY
FOR FINANCE 5 equality
Value comparison 6 comparison
Order comparison
7
Equality comparison identity comparison
Dr. Zhao Yibao
Senior Lecturer
Identity comparison 8
Of Quantitative
Finance
SMU Classification: Restricted
Slide
126
002/149

f(1)<f(2) and f(2)<f(3)


f(1)<f(2) and f(2)>=f(3) and f(3)<f(4)

formatted output QF205


COMPUTING
TECHNOLOGY
f(2) is FOR FINANCE
evaluated only once.

f(2) is
evaluated only once. Dr. Zhao Yibao
f(4) is not Senior Lecturer
Of Quantitative
evaluated. https://docs.python.org/3/tutorial/inputoutput.html#input-and-output Finance
SMU Classification: Restricted
Slide
127
001/149

Objects of different
types, except different
numeric types, never
QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

compare equal.
Dr. Z: Does it mean they are “not equal” or … ?
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
A Special Number: Infinity 128
002/149

Python non-unique inf: float('inf')


NumPy unique inf (singleton) : numpy.inf
Math unique inf (singleton) : math.inf

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
129
001/149

math.inf

Afloating-point positive infinity. (For


QF205 negative infinity, use -math.inf.)
COMPUTING
TECHNOLOGY
FOR FINANCE
Equivalent to the output of float('inf'). (New in
version 3.5.)

(Some examples are on the next slide.)

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
130
002/149

1
2
3
4
Every finite float
QF205
5
6
number is less than COMPUTING
TECHNOLOGY
FOR FINANCE

1 math.inf.
2
3
4
5 Dr. Zhao Yibao
Senior Lecturer
6 Of Quantitative
Finance
SMU Classification: Restricted
Slide
131
001/149

Strings (instances of str) compare


lexicographically using the
QF205
COMPUTING numerical Unicode code
TECHNOLOGY
FOR FINANCE
points (the result of the built-in function ord())
of their characters.

Dr. Z: We have seen some examples. 😁😁😁😁😁😁


Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
132
001/149

Sequences (instances of tuple, list, or range) can be


compared only within each of their types, with the

restriction that ranges do not support order


QF205
COMPUTING comparison. Equality comparison across
TECHNOLOGY
FOR FINANCE
these types results in inequality, and ordering

comparison across these types raises TypeError.


(see example on the next slide)
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
1 133
002/149

QF205
4 COMPUTING
TECHNOLOGY
FOR FINANCE

1.Compare within the same type of sequence.


2.Ranges do not support order comparison.
3.Equality comparison across types results inequality. Dr. Zhao Yibao
Senior Lecturer
4.Order comparison across types raises TypeError. Of Quantitative
Finance
SMU Classification: Restricted
Slide
134
001/149

Sequences compare lexicographically


QF205 using comparison of corresponding
COMPUTING
TECHNOLOGY
FOR FINANCE
elements, whereby reflexivity of the elements is enforced.
Dr. Z: We have seen some examples. 😁😁😁😁😁😁

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
135
001/149

The if statement
QF205
COMPUTING
TECHNOLOGY https://docs.python.org/3/reference/compound_stmts.html#the-if-statement
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
136
002/149
Flow Chart:

if condition: False
condition
indentedStatementBlock
QF205
COMPUTING
True TECHNOLOGY
FOR FINANCE

# t has a value already indentedStatementBlock


if t<19:
print('Walk to City Hall.')
print('Have dinner at DTF.')
print('Walk back to school.') Dr. Zhao Yibao
print('Take a bus home.') Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
137
002/149

True

False QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
138
001/149
if condition:
indentedStatementBlock1
else:
indentedStatementBlock2

(Dr. Z: Only one block Flow Chart:


QF205 is executed.)
COMPUTING
TECHNOLOGY
FOR FINANCE
True False
condition

indentedStatementBlock1 indentedStatementBlock2
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
139
001/149

False
Flow Chart:
c1
True False
c2
if condition1:
True False
indentedStatementBlock1 iSB1 c3
elif condition2:
True
indentedStatementBlock2 iSB2 c4
False
elif condition3:
QF205
COMPUTING
indentedStatementBlock3 iSB3
True False
c5
TECHNOLOGY elif condition4:
FOR FINANCE indentedStatementBlock4 True
iSB4
elif condition5:
indentedStatementBlock5
else: iSB5
indentedStatementBlock6
iSB6
Dr. Zhao Yibao
Senior Lecturer
(Dr. Z: Only one block
Of Quantitative
Finance
is executed.)
SMU Classification: Restricted
Slide
Q: Write a Python program to … 5 minutes? 140
002/149

Case 1

QF205
Case 2 COMPUTING
TECHNOLOGY
FOR FINANCE

Case 3
Dr. Zhao Yibao
Senior Lecturer
Ans: y=12450.00 Of Quantitative
Finance
SMU Classification: Restricted
Slide
141
001/149

Dr. Z: Is this what you plan to code?


Dr. Z: Is the code reusable?

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Dr. Zhao Yibao else: elif 320_000<=x:


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
142
002/149

Dr. Z: Is this better?


Case 1 x<xi[0]
y=0

xi[i]<=x<xi[i+1]
y=bi[i]+mi[i]/100*(x-xi[i])
i=0, 1, ..., 8 QF205
COMPUTING
Case 2 OR TECHNOLOGY
FOR FINANCE
xi[i-1]<=x<xi[i]
y=bi[i-1]+mi[i-1]/100*(x-xi[i-1])
i=1, 2, ..., 9

xi[9]<=x
Dr. Zhao Yibao
Case 3 y=bi[9]+mi[9]/100*(x-xi[9]) Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
143
001/149
Using the list method append(), we can
combine case 2 and case 3 into one.

import math
xi=[20000, 30000, 40000, 80000, 120000, 160000, 200000, 240000, 280000, 320000]

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE
xi.append(math.inf)
x=150_000

xi=[20000, 30000, 40000, 80000, 120000, 160000, 200000, 240000, 280000, 320000, math.inf]

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted

xi=[20000, 30000, 40000, 80000, 120000, 160000, 200000, 240000, 280000, 320000, math.inf]
Slide
144
002/149
x=150_000

xi[i-1]<=x<xi[i]

The location of the first number in xi which is bigger than x: i


i=next(filter(lambda s: s[1]>x, enumerate(xi)))[0]
QF205
COMPUTING
If i=0 Case 1: y=0 TECHNOLOGY
FOR FINANCE
otherwise y=bi[i-1]+mi[i-1]/100*(x-xi[i-1])

if i==0: #case 1
y=0
else: #case 2 and case 3 Dr. Zhao Yibao
y=bi[i-1]+mi[i-1]/100*(x-xi[i-1]) Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
145
002/149

1
QF205
2
COMPUTING
TECHNOLOGY
3 FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Ans: y=12450.00 Of Quantitative
Finance
SMU Classification: Restricted
Slide
146
002/149

QF205
COMPUTING
TECHNOLOGY

Ans: y=62150.00
FOR FINANCE

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
147
002/149

QF205
COMPUTING
TECHNOLOGY
FOR FINANCE

Ans: y=0
Dr. Zhao Yibao
Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
148
001/149

W3-027 W4-113

W2-131

W4-100

W2-168 W2-168

W4-119 W4-098 W4-131

W4-110
QF205
COMPUTING W2-159 W2-080 W4-074
TECHNOLOGY
FOR FINANCE W2-091 W2-017

W4-061

W4-110

W2-059 W2-164

Dr. Zhao Yibao


Senior Lecturer
Of Quantitative
Finance
SMU Classification: Restricted
Slide
149
001/149
Next week, we’ll learn

More Containers (Range, Set and Dictionary)


Loops (the for Statement, the while Statement)
QF205 break and continue Statements, and else Clause on
COMPUTING
TECHNOLOGY
FOR FINANCE Loops
Use of the Debugger (in the Spyder)
Solution to the Pandigital Formula Problem
Dr. Zhao Yibao
Senior Lecturer Comprehensions
Of Quantitative
Finance

You might also like