An Introduction to the Python Programming Language Daniel Toppo Pictet Asset Management

20192 – Financial Econometrics 2

Spring 2017 Python

Part I

Introduction

Intro Lecture 2 Python

What is Python ?

Intro Lecture 3 What is Python ?

High-level

Cross- Open platform Source

PYTHON Programming Language

Multi- Interactive paradigm

General- purpose

Intro Lecture 4 What is Python ?

. A high-level, general-purpose, interactive programming language o Designed to communicate instructions to a computer o Allows to humans to express what they want the computer to execute for them

. High-level o Python uses English keywords (aka natural language elements) o Strong abstraction from the details of the computer o Makes the process of creating a program much simpler . General-purpose o Used to create software in a wide variety of domains o Extended through an extensive ecosystem of libraries o Can be used for rapid code development as well as for building large applications

Intro Lecture 5 What is Python ?

. Interactive o Processed at runtime by Python interpreter (Matlab-like) o The interpreter is a program that reads a program and carries out its instructions o It translates the code at runtime to executable byte code (i.e. binary code that the computer can understand and execute)

. Cross-platform o Available for the most important Operating Systems (Windows, Mac OS, Linux, etc.) o Used to build web applications, desktop applications, etc. . Multi-paradigm o Supports different ways to program o Object-oriented, Functional, Imperative, Procedural programming

Intro Lecture 6 Python

What for ?

Intro Lecture 7 Where to find Python ?

. Domains o Software Development o Art (Movies) o Business o Education o Government o Science o Engineering . Available platforms o Windows o Mac OSX o Linux o MS-DOS o Solaris o Raspberry o Mobile phone (Android, iOS, Windows)

Intro Lecture 8 What is Python used for?

Web Data Development Analysis

Machine Learning

Intro Lecture 9 What is Python used for ?

Internet of Things Games

And Mobile LOT Development more!

Intro Lecture 10 What is Python used for ?

. Web Development o To create websites with dynamic content o Some popular (packages which allow developers to write web applications): , TurboGears,

. Data analysis o Large and excellent scientific libraries: NumPy, SciPy, Statsmodels, Pandas, Matplotlib, Seaborn, etc. o Specifically, Pandas is probably the most useful data analysis in Python: easy-to-use data structures and data analysis tools

. Machine Learning o Machine Learning is a branch of computing science that studies algorithms allowing computers to learn without being explicitly programmed o It is an application of a broader concept of Artificial Intelligence

Intro Lecture 11 What is Python used for ?

. Internet of Things o Python can be used to control and automate your entire home! o Python can act as a brain for robots to perform actions or act & react to the environment o Tiny computer like Raspberry Pi can be programmed in Python . Games Developments o Entire video games are coded in Python o From graphical interface, to artificial intelligence algorithms o Specifically, the Pygame library is used to program games . Mobile Developments o Some library (like Kivy, or PyMob) allow for rapid development of mobile applications o Still a very young technology though, but might improve drastically in the near future Intro Lecture 12 Who uses Python ?

Intro Lecture 13 Python

Tools & Infrastructure

Intro Lecture 14 Python Tools & Infrastructure

. Python tools and infrastructure are all the components (software & hardware) that allow for increasing productivity

. Anaconda is one of the most popular Python distribution for data science o To install Python and scientific libraries o Over 100 of the most important libraries o Cross-platform (Windows, Mac, Linux)

Intro Lecture 15 Python Tools & Infrastructure

. iPython is a Python interactive interpreter o syntax color highlighting o code completion o variables inspection o integrated help o commands history o cross-platform

Intro Lecture 16 Python Tools & Infrastructure

. Spyder IDE (Integrated Development Environment) is a Python editor with: o syntax color highlighting o code auto-completion o variables inspection o integrated help

Intro Lecture 17 Python Tools & Infrastructure

. PyCharm is another Python IDE: o syntax color highlighting o code auto-completion o debugging capabilities o variables inspection o built-in web development integration o free student access for professional edition

Intro Lecture 18 Python

Why use Python ?

Intro Lecture 19 Why use Python ?

. Python is easy ! o Easy to read – Easy to learn – Easy to digest!

o In C++ (another very famous programming language) : #include void main() { cout << “Ciao Italia!" << endl; }

o In Python : print (“Ciao Italia!")

Intro Lecture 20 Why use Python ?

. Python's ecosystem is one of the largest out of any programming community: External libraries Tools Frameworks

Books

Documentation Websites

Tutorials Python’s Python’s ecosystem Developers People Trainers

Intro Lecture 21 Why use Python ?

. Widely taught in universities o Top-ranked tech universities (MIT, Berkeley, etc.) switched their introductory courses to Python o The largest MOOC (massive open online course) providers (edX, Coursera, Udacity) offer introductory programming course in Python

. Open source o Development model that encourages open collaboration o Python source code is freely available to the public o Higher security, higher quality, higher customization . One of the top-ten programming languages rd 1 o IEEE Spectrum: 3 out of 20 (July 2016) th 2 o TIOBE Programming Community : 5 out of 20 (Feb. 2017) 1 http://spectrum.ieee.org/computing/software/the-2016-top-programming-languages 2 http://www.tiobe.com/tiobe-index/ Intro Lecture 22 Python vs Matlab

Python Matlab . Advantages . Advantages Include IDE, GUI builder, o Open and free o matrix algebra, data o Low learning curve processing, plotting in o Object oriented standard package o High portability: run the code everywhere o Available and extensive documentation o Extensive ecosystem:  libraries (external modules) o Large scientific community  GUI toolkits (tools to build Graphical User Interfaces) . Disadvantages  IDEs (Integrated Proprietary: hidden code Development Environment) o o Expensive: Toolboxes are . Disadvantages usually not free Low portability (Matlab o Must include libraries to o extend standard code doesn't run exactly the functionalities same way on different platforms) Intro Lecture 23 Python vs Matlab

Python Matlab Core Core . Programming language . Programming language . Interpreter . Interpreter . Standard library . Standard library . IDE . GUI builder

Libraries IDEs Toolkits | Toolboxes . Numpy . Spyder . Simulink (simulation & . Scipy . PyCharm . Matplotlib . Wing IDE modelling) . Pandas . PyStudio . Parallel computing . Scikit . IDLE . Image processing . PyQt4 . Etc. . Signal processing . Etc. . Etc.

Intro Lecture 24 Python

Python in Finance

Intro Lecture 25 Python in Finance

. Financial institutions are evolving into technology companies o Banking and financial institutions is the industry that spends the most in technology (often spending billions $US per year) o Large banks employ thousands of developers to create and maintain IT systems

. Technology leads to competitive advantages o Increase of speed of trades executions o Increase and automation of controls o Ease of increasing data volumes management o Financial engineering modelling . However, skilled people are scarce and hard to find o Expert not only need to know technology, but also finance! o Skills shortages are a threat to competitiveness and growth

Intro Lecture 26 Python in Finance

. Non-exhaustive list of uses of Python in finance o Analyzing data o Backtesting trades and models o Financial modeling o Asset pricing o Risk management . Examples of software built with Python in the financial Industry o JP Morgan’s Athena: risk management & analysis, asset pricing, trading management system o Bank of America Merrill Lynch’s Quartz: asset pricing, positions management, risk management o Bellco Credit Union’s SAFE: online banking system o Altis Investment Management: risk management system

Intro Lecture 27 Python in Finance

. Most requested languages in coding interviews in the financial space (from the HackerRank1 website)

1 https://blog.hackerrank.com/emerging-languages-still-overshadowed-by- incumbents--python-in-coding-interviews/ Intro Lecture 28 Python

Part II

Examples

Intro Lecture 29 Python Examples – Basic

. Simple mathematical expression and its evaluation: Compound Interest = 1 + 𝑡𝑡 # Defines a function with 𝐹𝐹parameters𝑃𝑃 � 'p', 𝑟𝑟'r' and 't' def compoundInterest (p, r, t) : return p*(1+r)**t # Return the function result

# Let's initialize the parameters… p = 100 r = 0.1 t = 10

# … and call the function ! f = compoundInterest (p, r, t) # The variable 'f' yields the # function result (259.374246…)

Intro Lecture 30 Python Examples – Basic

. What does this very simple example shows us: o Python syntax is very similar to the mathematical syntax o Python uses English keywords for expressing scientific and mathematical problems o Python elegant syntax clearly separates blocs of statements (the function in our example) using adequate indentation

. Any financial (or scientific) problem can thus be very easily expressed and translated into algorithms

Intro Lecture 31 Examples – Optimization

. Let’s try to minimize the following function over the [-1, 1] x [-1, 1] space: 1 , = sin + 2 2 𝑥𝑥 𝑓𝑓 𝑥𝑥 𝑦𝑦 𝑝𝑝𝑝𝑝 � 𝑥𝑥 � 𝑦𝑦 𝑥𝑥 − 𝑒𝑒

Intro Lecture 32 Examples – Optimization

. From the plot, minima are located at around: o (x = 1.0, y = -0.5) o (x = -0.5, y = 1.0) # Defines the function def f(params) : x, y = params return sin(pi*x*y) + x**2 - exp(x)

# Let’s fix our search space to [-1, 1]:[-1, 1] bnds = ((-1, 1), (-1, 1)) # And our first initial guess for the optimizer initGuess = [-0.5, 0.5]

# Finally, optimize ‘f’ using the ‘minimize’ function optimization = optimize.minimize(f, initGuess, method="SLSQP", bounds=bnds)

Intro Lecture 33 Examples – Optimization

. Results # Prints the result print (optimization)

fun: -2.417917900528793 message: 'Optimization terminated successfully.‘ nit: 5 success: True x: array([-0.423265, 1.0]) . The optimization results is successful, with results o x = [-0.42, 1.0], close to what we were expecting o yielding function value: -2.42

. We can do the same exercise with another initial guesses to find another minimum (e.g. [0.75, -0.75])

Intro Lecture 34 Examples – Linear Regression

. Dataset is about salaries of professors. The data were collected to monitor salary differences between male and female members . 397 observations on the following 6 variables o rank: AssocProf, AsstProf, Prof o discipline: A (theoretical), B (applied) department o yrs.since.phd: years since PhD o yrs.service: years of service o sex: Female, Male o salary: nine-month salary, in $US . Dependent variable: salary . Independent variables: years service, years since PhD

Intro Lecture 35 Examples – Linear Regression

. Linear regression function # Read the data series from “salaries.xlsx” Excel file xslx = ExcelFile("salaries.xlsx") # Parse the “salaries” sheet and store the data into the “data” variable data = xslx.parse("salaries")

regressor = "salary" # response predictor = "yearsOfService" # predictor

y = data[regressor] X = data[predictor] X = add_constant(X) # Adds a constant term to the predictor

# OLS is the Ordinary Least Squares function model = OLS(y, X).fit()

Intro Lecture 36 Examples – Linear Regression

. Result # Prints the regression model print (model)

Intro Lecture 37 Examples – Linear Regression

. Plotting salaries regression against years of service

Intro Lecture 38 Examples – Linear Regression

. Plot – separating women & men salaries

Intro Lecture 39 Examples – Linear Regression

. Plot – separating theoretical to practical departments

Intro Lecture 40 Python

References

Intro Lecture 41 Python - References

Online documentation

. Official Python website: https://docs.python.org/3/ . Wiki-Book: https://en.wikibooks.org/wiki/Python_Programming . Byte of Python: http://www.swaroopch.com/notes/Python . Python Bibliotheca: http://openbookproject.net/pybiblio/ . Tutorialspoint: https://www.tutorialspoint.com/python . Google: https://developers.google.com/edu/python/ . Pythonspot: https://pythonspot.com/ . Pythonlearn: http://www.pythonlearn.com/book.php . Python for Fun: http://www.openbookproject.net/py4fun/ . Pandas: http://pandas.pydata.org/ . Numpy: http://www.numpy.org/ . Scipy: https://www.scipy.org/

Intro Lecture 42 Python - References

Books

Mark Lutz Learning Python, 5th Edition O'Reilly Media; 5 edition (July 6, 2013)

Paul Jones Python: The Fundamentals Of Python Programming CreateSpace Publishing Platform (Oct. 26, 2016)

Eric Matthes Python Crash Course: A Hands-On, Project- Based Introduction to Programming No Starch Press; 1 edition (November 30, 2015)

Intro Lecture 43 Python - References

Books

Yves Hilpisch Python for Finance

O′Reilly (Dec. 30, 2014)

Wes McKinney Python for Data Analysis O'Reilly Media (Jul. 31, 2016)

Intro Lecture 44