HKUST2023 Python HSC Lecture1
HKUST2023 Python HSC Lecture1
FINANCE IN PYTHON
Lecture I – Introduction to Python Programming
MAFS5360 – Summer, 2023
Copyright © by Dr. Hongsong Chou, 2019 - 2023. No part of this material may be: (i) copied, photocopied, or duplicated in any form, by any means,
1
or (ii) redistributed without prior expressed consent from the author. The views expressed here are those of the author himself and himself only.
AGENDA
• Outline of the course
2
AGENDA
• Outline of the course
3
WHAT THIS COURSE IS ABOUT
• This course teaches the basics of Python programming, with a strong
focus on how to use Python the programming language to solve
problems in finance, especially secondary market trading,
quantitative modeling and forecasting;
• We will cover a fair amount of basic knowledge of Python
programming, including set-up of the environment, data types,
variables and logics, and object-oriented programming paradigm;
• We will also cover Python programming skills related to files,
functions, libraries, etc.;
• We will move forward to parallel programming in Python and
performance measurement/optimization;
• In and out of our classes, students will spend a fair amount of time
of this course on “student-led projects”, where different teams will
“get their hands dirty” with real projects in Python, especially
projects that allow them to learn the language within a financial
4
application background.
GRADING AND OTHER ADMIN MATTERS
• Grading:
- There will be five quizzes, given in class, that will take in total
50% of the final grade;
- Late or no submission of quiz will be given 0 score, unless
otherwise approved by the instructor;
- The other 50% of the final grade will be from the performance
of student-led projects;
- There will be NO mid-term or final exams;
- Most of the quizzes will be coding samples which students will
be asked to build on in order to achieve certain programming
results; occasionally (but rarely), I may give written quizzes, too;
• Python environment: We will stick to Python 3;
• Instructor: Hongsong Chou ([email protected]); office hour: TBA;
• TA/Grader:
- Terry Xu ([email protected]).
5
(TENTATIVE) OUTLINE OF THE COURSE
• Lecture 1 (June 20/27): Basic Python programming – Data Structure
and object-oriented programming
• Lecture 2 (June 29/July 6): Utilities in Python programming – File I/O
and financial time series handling
• Lecture 3 (July 8/13): Discussions on student-led projects, and
project kick-offs;
• Lecture 4 (July 15/20): Machine learning through Python
programming – packages and best practices
• Lecture 5 (July 22/27):Parallel computing and performance
optimization in Python programming
• Student-led presentations - Team A (August 3)
• Student-led presentations - Team B (August 5)
7
RELATION BETWEEN DIFFERENT PROJECTS
• An illustration of a typical quantitative trading system:
Research Platform
Strat
N+1
PMS (Position
Strat Strat Strat Strat management system)
A B C N
Interface
MDS System
(market
layer
data
services)
HDB
(historical Exchange A Exchange B
database) SDS
Data sources
(static
data
for instruments,
etc.
8
services)
PERSONAL CODING EXPERIENCE
• Started with “Basic” in high school in the 1980s, just for fun;
10
AGENDA
• Outline of the course
11
PYTHON LANGUAGE BASICS
• Open source (a.k.a., free);
• Widely-used;
• High-level (vs. assembly or C);
• General purposed (instead of specific such as HTML, etc.);
• Interpreted (vs. compiled);
• Object-oriented;
• Functional/procedural;
• Great libraries to use for various purposes;
• Recent emergence of A.I. and its implementations via Python.
12
Python installation
• Python 3.x will be used in this course;
• Installation via Anaconda:
https://www.anaconda.com/download#downloads
13
PYTHON CODING ENVIRONMENTS
• Spyder
• PyCharm
• Eclipse
• Pros of IDEs:
- Easy navigation through code;
- Debugging;
- Project management;
- Collaborations if needed
• Cons of IDEs:
- Heavy (vs. command lines);
- Stability.
14
A BRIEF INTRO TO JUPYTER NOTEBOOK
• Jupyter notebook is often used as a convenient tool to test code
snippets;
• It can be downloaded from https://jupyter.org/install;
• Let see a few examples using the attached file Jupyter Notebook
Introduction.ipynb.
15
PYTHON CODING BASICS (I)
• A few simple lines:
• Run on command:
• Run in IDE:
16
PYTHON CODING BASICS (II)
• Assignment: =
• Multi-assignments in Python is OK:
- x, y = 12, 13
• Comparison: ==
• Operators: +, -, *, /, %, etc. for numbers
• Logical operators: and, or, not
• Variables in Python:
- no need to declare first (but you need to assign something to it
before referring to it; such assignment is also called “binding”);
- no type needs to be specified (although I’d encourage to do so
in function arguments, as we will discuss later); this also means
that Python does not have “intrinsic types”;
- once a variable is bound with a value via assignment, the “de-
construction” of the variable when it is no longer used will be
done through Python’s Garbage Collector (more details on GC in
17
later lectures);
MORE ON PYTHON VARIABLES
• Naming rules:
- Case sensitive;
- Don’t start with a number;
- Here are the reserved words:
18
ASSIGNMENT THROUGH REFERENCE
• x = 3
- a block of memory is created to store an integer 3;
- a variable x is created that references to the block of memory;
that is, the address of the memory that stores integer 3 is linked
to variable x;
• x = y
- In Python, values are passed by “assignment”, which means
that, depending on whether the variable on the right-hand side
of “=” is mutable or immutable, changing the value in y above
may or may nor change the value of x. So, just be careful! (see
examples in attached jupyter notebook
PythonBasics.ipynb);
- Python maintains an ID for each object it creates; an object that
allows you to change its values without changing its identity is a
mutable object; the changes that you can perform on a mutable
19
object’s value are known as mutations.
PYTHON BASIC DATA TYPES
• Integers:
- Decimals: 1, 2, -3, -4, …
- Python 3 is 64bits so an integer in Python 3 can be of any length
- Other basis: Binary (0b or 0B prefix), Octal (0o or 0O prefix),
Hexadecimal (0x or 0X prefix);
• Float:
- 1.2, 3.1415926
- Almost all platforms represent Python float values as 64-bit
“double-precision” values, according to the IEEE 754 standard;
• Complex: 2+3j
• String: ‘A’, ‘hello’, ‘\n’, ‘\\’, etc.
• Boolean: True, False
• To get the basic type, one can use the “type” function:
- type(0X10);
- print(str(0X10)).
20
PYTHON COMMENTS
• Within one line, one can use # and the rest of the line is ignored;
• To comment out multiple lines, it will be best to use triple quotes:
21
MUTABLE VS IMMUTABLE
22
PYTHON BUILT-IN TYPES
• Tuples:
- Sequence of immutable Python objects (a.k.a., elements cannot
be modified)
- a = (1,2,3)
- a[0] = 1
• List:
- Sequence of mutable Python objects (a.k.a., elements cannot
be modified)
- b = [1,2,3]
- b[0] = 1
• Dictionary:
- Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly
braces;
- c = {‘a’:[1,2,3], ‘b’:[4,5,6]}
23
- c[‘a’] = [1,2,3]
PYTHON LOGIC FLOWS
• if – elif – else:
- if (1 == 2):
print(str(‘will never get here’))
elif (2 == 2):
print(str(‘of course’))
else:
print(str(‘no need’))
• for:
- for i in range(100):
print(str(i))
• while:
- i = 0
while i < 10:
24
print(str(i))
i += 1
AGENDA
• Outline of the course
25
OBJECT-ORIENTED PROGRAMMING
• It is first and foremost a programming paradigm:
- Model the world as a collection of objects that interact with
each other;
- Each object must have some “states” or “features” that can
change with time (for example) or be changed by other object’s
interaction;
- The interaction between two objects is often pre-defined (such
as I assign homework to students, and students submit finished
assignments to me);
• Fields:
- These are essentially the features of an object, such as
name/age/height/weight/… of a human being;
• Methods:
- These are essentially the actions an object can take, such as
eat/drink/talk/… of a human being.
26
PYTHON CLASS
• Python class is a programming manifestation of an object in the O-O
paradigm:
27
PYTHON CLASS EXAMPLES
• The following classes will be demonstrated to illustrate the ideas of
encapsulation, polymorphism, and inheritance concepts of object
oriented programming:
- Class Strategy;
- Class Order;
- Class Position;
- Class Execution.
28
AGENDA
• Outline of the course
29
EXCEPTION EXAMPLES
30
PYTHON BUILT-IN EXCEPTIONS
Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
OverflowError Raised when result of an arithmetic operation is too large to be represented.
ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by next() function to indicate that there is no further item to be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a function or method, but no value has been bound to that var
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
ValueError Raised when a function gets argument of correct type but improper value.
ZeroDivisionError Raised when second operand of division or modulo operation is zero.
31
EXCEPTION HANDLING
• The try – except – else clause:
- try part will execute until an exception is raised;
- then the execution jumps to the except line, which often
determines what kind of specific exception needs to be
handled;
- If the except line finds that the raised exception is not intended
for it to handle, then the execution jumps to the else portion,
which is essentially a “clean up” operation.
32
USER-DEFINED EXCEPTIONS
• The following classes will be demonstrated to illustrate the ideas of
encapsulation, polymorphism, and inheritance concepts of object-
oriented programming:
- Class Strategy;
- Class Order;
- Class Position;
- Class Execution.
33
THAT’S ALL FOR THIS LECTURE.
THANK YOU!
34