SlideShare a Scribd company logo
1 of 25
Download to read offline
Python. Finance. Excel.
• The Thalesians, Zürich
June 9th, 2016 Felix Zumstein, CFA
About me
• Consultancy:
– Analytical apps for Excel & web
– Professional support/training for xlwings
• Previously:
– 9yrs in Banking /Asset Management
– Background: Finance & Economics
2
About this talk
3
This talk is NOT about sophisticated models that
make you rich.
This talk is about HOW to implement classic
financial models using Python and Excel.
Download the material from:
https://github.com/ZoomerAnalytics/talks
Agenda
4
1) Portfolio Optimization
• Intro to fundamental packages for finance
• xlwings: Interactive use
2) Monte Carlo Simulation
• Simulation with NumPy
• xlwings: From Excel macros to web apps
3) Option Pricing and Implied Volatility
• Introduction to QuantLib
• xlwings: User Defined Functions (UDFs)
4) Save the Spreadsheet
1 Portfolio Optimization
xlwings: Interactive use
Jupyter Notebook
6
This demo gives an introduction to:
• Jupyter notebook
• Pandas
• xlwings
• Matplotlib/Seaborn
• Plotly
• SciPy
• cvxopt
xlwings: Basic Syntax
7
>>>  from  xlwings import  Workbook,  Range
>>>  wb =  Workbook(…)
>>>  Range("A1").value  =  my_variable
>>>  Range("A1").options(pd.DataFrame,
expand="table").value
my_variable: Strings, numbers, DateTime, lists
(nested), NumPy arrays, Pandas DataFrames, …
cvxopt
8
• GPL license (SciPy: BSD)
• Installation:
- Mac/Linux: conda install  cvxopt
- Windows: Download wheel from
http://www.lfd.uci.edu/~gohlke/pythonlibs/#cvxopt
then pip install it
• CVXPY: Python-embedded modeling language
for convex optimization problems. It wraps the
solvers cvxopt, ECOS and SCS (cvxpy.org).
2 Monte Carlo Simulation
xlwings: Excel Macros
10
Random walk
𝑑𝑆# = 	
   𝜇 𝑆# 𝑑𝑡	
   + 	
   𝜎 𝑆# 𝑑𝑊#
In the Black-Scholes model, asset prices 𝑆# are assumed to follow a
geometric Brownian motion (GBM), as defined by this stochastic
differential equation (SDE):
𝜇: drift, 𝜎: volatility, 𝑊#: brownian motion
Discrete time version:
𝑆# = 𝑆#+,# exp 𝜇 −
𝜎1
2
Δ𝑡	
   + 	
   𝜎 𝜀# Δ𝑡
S[0,  :]  =  starting_price
for t  in range(n_timesteps):
rand_nums =  np.random.randn(n_simulations)
S[t  + 1,  :]  =  S[t,  :]  * np.exp((mu  -­‐ 0.5  * vol ** 2)  * dt +
vol * rand_nums * np.sqrt(dt))
Python: (for full context look at the repo as mentioned on slide 13)
Same code, different front end
11
simulation.py
xlwings_app.py web_app.py
Prototype analytical web apps
12
vs.
Source code and hosted app
13
Hosted Sample: www.zoomeranalytics.com/simulation-demo
Source Code: https://github.com/ZoomerAnalytics/simulation-demo
xlwings: Call Python from VBA
14
Sub MyFunction()
RunPython ("import  module;module.func()")
End  Sub
def func():
wb =  xw.Workbook.caller()
module.py
VBA:
3 Option Pricing &
Implied Volatility
xlwings: UDFs
QuantLib
16
• Open-source framework for quant finance. Released in
2000 and written in C++ with bindings for many languages.
• ”Offers […] features such as market conventions, yield curve
models, solvers, PDEs, Monte Carlo (low-discrepancy
included), exotic options, VAR, and so on.” (quantlib.org)
• Installation
- Windows: Download the Python wheel from
http://www.lfd.uci.edu/~gohlke/pythonlibs/#quantlib
and pip-install it
- Linux: apt-­‐get  install  quantlib-­‐python  quantlib-­‐swig
- Mac: Err…Right now, no binaries (wheels or conda
package) and building it is not exactly fun
PyQL
17
• The official Python bindings for QuantLib (“quantlib-python”)
are created with SWIG (Simplified Wrapper and Interface Generator)
• Enthought started the PyQL project that uses Cython instead
of SWIG. PyQL offers (from the PyQL docs):
- Integration with standard datatypes (like datetime objects) and
numpy arrays;
- Simplified API on the Python side (e.g. usage of Handles
completely hidden from the user);
- Support full docstring and expose detailed function signatures to
Python;
- Code organised in subpackages to provide a clean namespace,
very close to the C++ code organisation;
- Easy extendibility thanks to Cython and shorter build time when
adding new functionalities;
- Sphinx documentation.
• However, PyQL covers only a fraction of the official bindings.
Options: Implied Volatility
18
Implied volatility is the volatility that makes the option
price calculated by a model equal to its observed
market price.
𝐶 𝐹, 𝜏 = 𝐷(𝑁 𝑑< 𝐹 − 𝑁 𝑑+ 𝐾)
𝑑± =	
  
1
𝜎 𝜏	
  
log
𝐹
𝐾
±
1
2
𝜎1
𝜏
Black-Scholes formula (alternative formulation):
𝑃 𝐹, 𝜏 = 𝐷(𝑁 −𝑑+ 𝐾 − 𝑁 −𝑑< 𝐹)
𝐶, 𝑃: Call/Put Option, 𝐷: discount factor, 𝐹 = 𝑆E 𝑒 G+H I: forward price,
𝑁(J): cumulative distribution function of std normal distribution,
𝜎: volatility of returns of underlying asset, 𝐾: Strike, 𝜏: time to
maturity, 𝑟: cont. comp. risk-free rate, 𝑞: dividend yield
xlwings: UDFs
19
@xw.func
@xw.arg("x",  pd.DataFrame)
def myfunction(x):
return x
4 Save the Spreadsheet
xlwings: VBA unit tests
Tough times for spreadsheet models
21
"Where a bank relies on manual processes and
desktop applications (e.g. spreadsheets, databases)
and has specific risk units that use these applications
for software development, it should have effective
mitigants in place (e.g. end-user computing policies
and procedures) and other effective controls that are
consistently applied across the bank's processes. "
– Basel Committee on Banking Supervision, Principle 3
Unit Tests
22
• Automated unit tests are a cornerstone of modern
software development (”test-driven development”)
• Excel: doesn’t offer any means to create unit tests
(there’s Debug.Assert, but that doesn’t really help)
• Python: has a built-in unit test module
• Unit testing with xlwings is unintrusive:
- No add-in to be installed
- No changes to the original VBA code base
- Python standard lib + xlwings is all you need
• It’s a great way to verify & debug legacy VBA code
Running VBA code with xlwings
23
xlwings has a beauuuutiful interface to access VBA
Subs and Functions:
VBA:
Function MySum(x,  y)
MySum =  x  +  y
End  Function
Python:
>>>  wb = xw.Workbook.active()
>>>  my_sum = wb.macro('MySum')
>>>  my_sum(1,  2)
3
Testing with xlwings
24
xlwings allows you to:
• Unit test spreadsheets with or without VBA code
• Test VBA code against an alternative
implementation in Python (incl. any third party
packages like SciPy or QuantLib that are usually
heavily tested)
Demo: Prime numbers
Questions?

More Related Content

Viewers also liked

Creating Excel files with Python and XlsxWriter
Creating Excel files with Python and XlsxWriterCreating Excel files with Python and XlsxWriter
Creating Excel files with Python and XlsxWriterjmncnamara
 
Python + Excel
Python + Excel Python + Excel
Python + Excel POSTECH
 
xlwings - Connecting Python with Excel
xlwings - Connecting Python with Excelxlwings - Connecting Python with Excel
xlwings - Connecting Python with Excelxlwings
 
Structured Data Challenges in Finance and Statistics
Structured Data Challenges in Finance and StatisticsStructured Data Challenges in Finance and Statistics
Structured Data Challenges in Finance and StatisticsWes McKinney
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 

Viewers also liked (6)

Creating Excel files with Python and XlsxWriter
Creating Excel files with Python and XlsxWriterCreating Excel files with Python and XlsxWriter
Creating Excel files with Python and XlsxWriter
 
Python + Excel
Python + Excel Python + Excel
Python + Excel
 
xlwings - Connecting Python with Excel
xlwings - Connecting Python with Excelxlwings - Connecting Python with Excel
xlwings - Connecting Python with Excel
 
Structured Data Challenges in Finance and Statistics
Structured Data Challenges in Finance and StatisticsStructured Data Challenges in Finance and Statistics
Structured Data Challenges in Finance and Statistics
 
Biz plan
Biz planBiz plan
Biz plan
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similar to Python. Finance. Excel. - The Thalesians

Pitfalls of machine learning in production
Pitfalls of machine learning in productionPitfalls of machine learning in production
Pitfalls of machine learning in productionAntoine Sauray
 
WSO2 Complex Event Processor - Product Overview
WSO2 Complex Event Processor - Product OverviewWSO2 Complex Event Processor - Product Overview
WSO2 Complex Event Processor - Product OverviewWSO2
 
Apache Flink Adoption at Shopify
Apache Flink Adoption at ShopifyApache Flink Adoption at Shopify
Apache Flink Adoption at ShopifyYaroslav Tkachenko
 
[2016/2017] Modern development paradigms
[2016/2017] Modern development paradigms [2016/2017] Modern development paradigms
[2016/2017] Modern development paradigms Ivano Malavolta
 
DSD-INT 2014 - OpenMI Symposium - Federated modelling of Critical Infrastruct...
DSD-INT 2014 - OpenMI Symposium - Federated modelling of Critical Infrastruct...DSD-INT 2014 - OpenMI Symposium - Federated modelling of Critical Infrastruct...
DSD-INT 2014 - OpenMI Symposium - Federated modelling of Critical Infrastruct...Deltares
 
Making Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFluxMaking Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFluxTrayan Iliev
 
WSO2 Machine Learner - Product Overview
WSO2 Machine Learner - Product OverviewWSO2 Machine Learner - Product Overview
WSO2 Machine Learner - Product OverviewWSO2
 
MLFlow: Platform for Complete Machine Learning Lifecycle
MLFlow: Platform for Complete Machine Learning Lifecycle MLFlow: Platform for Complete Machine Learning Lifecycle
MLFlow: Platform for Complete Machine Learning Lifecycle Databricks
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگوrailsbootcamp
 
Adtech scala-performance-tuning-150323223738-conversion-gate01
Adtech scala-performance-tuning-150323223738-conversion-gate01Adtech scala-performance-tuning-150323223738-conversion-gate01
Adtech scala-performance-tuning-150323223738-conversion-gate01Giridhar Addepalli
 
Adtech x Scala x Performance tuning
Adtech x Scala x Performance tuningAdtech x Scala x Performance tuning
Adtech x Scala x Performance tuningYosuke Mizutani
 
SE_Module1new.ppt
SE_Module1new.pptSE_Module1new.ppt
SE_Module1new.pptADARSHN40
 
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...OpenWhisk
 
Webinar: Começando seus trabalhos com Machine Learning utilizando ferramentas...
Webinar: Começando seus trabalhos com Machine Learning utilizando ferramentas...Webinar: Começando seus trabalhos com Machine Learning utilizando ferramentas...
Webinar: Começando seus trabalhos com Machine Learning utilizando ferramentas...Embarcados
 
Implementing Messaging Patterns in JavaScript using the OpenAjax Hub
Implementing Messaging Patterns in JavaScript using the OpenAjax HubImplementing Messaging Patterns in JavaScript using the OpenAjax Hub
Implementing Messaging Patterns in JavaScript using the OpenAjax HubKevin Hakanson
 
Practical machine learning
Practical machine learningPractical machine learning
Practical machine learningFaizan Javed
 
Software development effort reduction with Co-op
Software development effort reduction with Co-opSoftware development effort reduction with Co-op
Software development effort reduction with Co-oplbergmans
 

Similar to Python. Finance. Excel. - The Thalesians (20)

Pitfalls of machine learning in production
Pitfalls of machine learning in productionPitfalls of machine learning in production
Pitfalls of machine learning in production
 
WSO2 Complex Event Processor - Product Overview
WSO2 Complex Event Processor - Product OverviewWSO2 Complex Event Processor - Product Overview
WSO2 Complex Event Processor - Product Overview
 
Oopp Lab Work
Oopp Lab WorkOopp Lab Work
Oopp Lab Work
 
Amit Bhandari
Amit BhandariAmit Bhandari
Amit Bhandari
 
Apache Flink Adoption at Shopify
Apache Flink Adoption at ShopifyApache Flink Adoption at Shopify
Apache Flink Adoption at Shopify
 
[2016/2017] Modern development paradigms
[2016/2017] Modern development paradigms [2016/2017] Modern development paradigms
[2016/2017] Modern development paradigms
 
DSD-INT 2014 - OpenMI Symposium - Federated modelling of Critical Infrastruct...
DSD-INT 2014 - OpenMI Symposium - Federated modelling of Critical Infrastruct...DSD-INT 2014 - OpenMI Symposium - Federated modelling of Critical Infrastruct...
DSD-INT 2014 - OpenMI Symposium - Federated modelling of Critical Infrastruct...
 
Making Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFluxMaking Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFlux
 
WSO2 Machine Learner - Product Overview
WSO2 Machine Learner - Product OverviewWSO2 Machine Learner - Product Overview
WSO2 Machine Learner - Product Overview
 
MLFlow: Platform for Complete Machine Learning Lifecycle
MLFlow: Platform for Complete Machine Learning Lifecycle MLFlow: Platform for Complete Machine Learning Lifecycle
MLFlow: Platform for Complete Machine Learning Lifecycle
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
Adtech scala-performance-tuning-150323223738-conversion-gate01
Adtech scala-performance-tuning-150323223738-conversion-gate01Adtech scala-performance-tuning-150323223738-conversion-gate01
Adtech scala-performance-tuning-150323223738-conversion-gate01
 
Adtech x Scala x Performance tuning
Adtech x Scala x Performance tuningAdtech x Scala x Performance tuning
Adtech x Scala x Performance tuning
 
SE_Module1new.ppt
SE_Module1new.pptSE_Module1new.ppt
SE_Module1new.ppt
 
PRELIM-Lesson-2.pdf
PRELIM-Lesson-2.pdfPRELIM-Lesson-2.pdf
PRELIM-Lesson-2.pdf
 
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
IBM Bluemix OpenWhisk: Serverless Conference 2016, London, UK: The Future of ...
 
Webinar: Começando seus trabalhos com Machine Learning utilizando ferramentas...
Webinar: Começando seus trabalhos com Machine Learning utilizando ferramentas...Webinar: Começando seus trabalhos com Machine Learning utilizando ferramentas...
Webinar: Começando seus trabalhos com Machine Learning utilizando ferramentas...
 
Implementing Messaging Patterns in JavaScript using the OpenAjax Hub
Implementing Messaging Patterns in JavaScript using the OpenAjax HubImplementing Messaging Patterns in JavaScript using the OpenAjax Hub
Implementing Messaging Patterns in JavaScript using the OpenAjax Hub
 
Practical machine learning
Practical machine learningPractical machine learning
Practical machine learning
 
Software development effort reduction with Co-op
Software development effort reduction with Co-opSoftware development effort reduction with Co-op
Software development effort reduction with Co-op
 

More from xlwings

xlwings for Google Sheets
xlwings for Google Sheetsxlwings for Google Sheets
xlwings for Google Sheetsxlwings
 
Cross-platform Spreadsheet Automation with Python
Cross-platform Spreadsheet Automation with PythonCross-platform Spreadsheet Automation with Python
Cross-platform Spreadsheet Automation with Pythonxlwings
 
Automate your PDF factsheets with xlwings Reports
Automate your PDF factsheets with xlwings ReportsAutomate your PDF factsheets with xlwings Reports
Automate your PDF factsheets with xlwings Reportsxlwings
 
Tech3camp Meetup: Python for Excel
Tech3camp Meetup: Python for ExcelTech3camp Meetup: Python for Excel
Tech3camp Meetup: Python for Excelxlwings
 
xlwings performance
xlwings performancexlwings performance
xlwings performancexlwings
 
Git for Excel (Webinar)
Git for Excel (Webinar)Git for Excel (Webinar)
Git for Excel (Webinar)xlwings
 
Deployment of xlwings-powered spreadsheets (webinar)
Deployment of xlwings-powered spreadsheets (webinar)Deployment of xlwings-powered spreadsheets (webinar)
Deployment of xlwings-powered spreadsheets (webinar)xlwings
 
xlwings reports: Reporting with Excel & Python
xlwings reports: Reporting with Excel & Pythonxlwings reports: Reporting with Excel & Python
xlwings reports: Reporting with Excel & Pythonxlwings
 
Python and Excel in Finance (PyData meetup Zurich)
Python and Excel in Finance (PyData meetup Zurich)Python and Excel in Finance (PyData meetup Zurich)
Python and Excel in Finance (PyData meetup Zurich)xlwings
 
Automated testing of Excel Workbooks
Automated testing of Excel WorkbooksAutomated testing of Excel Workbooks
Automated testing of Excel Workbooksxlwings
 
Git for Excel
Git for ExcelGit for Excel
Git for Excelxlwings
 
Automated Testing of Excel Workbooks
Automated Testing of Excel WorkbooksAutomated Testing of Excel Workbooks
Automated Testing of Excel Workbooksxlwings
 
Git for Excel files webinar
Git for Excel files webinarGit for Excel files webinar
Git for Excel files webinarxlwings
 
xlwings Zurich Python User Group Meetup
xlwings Zurich Python User Group Meetupxlwings Zurich Python User Group Meetup
xlwings Zurich Python User Group Meetupxlwings
 

More from xlwings (14)

xlwings for Google Sheets
xlwings for Google Sheetsxlwings for Google Sheets
xlwings for Google Sheets
 
Cross-platform Spreadsheet Automation with Python
Cross-platform Spreadsheet Automation with PythonCross-platform Spreadsheet Automation with Python
Cross-platform Spreadsheet Automation with Python
 
Automate your PDF factsheets with xlwings Reports
Automate your PDF factsheets with xlwings ReportsAutomate your PDF factsheets with xlwings Reports
Automate your PDF factsheets with xlwings Reports
 
Tech3camp Meetup: Python for Excel
Tech3camp Meetup: Python for ExcelTech3camp Meetup: Python for Excel
Tech3camp Meetup: Python for Excel
 
xlwings performance
xlwings performancexlwings performance
xlwings performance
 
Git for Excel (Webinar)
Git for Excel (Webinar)Git for Excel (Webinar)
Git for Excel (Webinar)
 
Deployment of xlwings-powered spreadsheets (webinar)
Deployment of xlwings-powered spreadsheets (webinar)Deployment of xlwings-powered spreadsheets (webinar)
Deployment of xlwings-powered spreadsheets (webinar)
 
xlwings reports: Reporting with Excel & Python
xlwings reports: Reporting with Excel & Pythonxlwings reports: Reporting with Excel & Python
xlwings reports: Reporting with Excel & Python
 
Python and Excel in Finance (PyData meetup Zurich)
Python and Excel in Finance (PyData meetup Zurich)Python and Excel in Finance (PyData meetup Zurich)
Python and Excel in Finance (PyData meetup Zurich)
 
Automated testing of Excel Workbooks
Automated testing of Excel WorkbooksAutomated testing of Excel Workbooks
Automated testing of Excel Workbooks
 
Git for Excel
Git for ExcelGit for Excel
Git for Excel
 
Automated Testing of Excel Workbooks
Automated Testing of Excel WorkbooksAutomated Testing of Excel Workbooks
Automated Testing of Excel Workbooks
 
Git for Excel files webinar
Git for Excel files webinarGit for Excel files webinar
Git for Excel files webinar
 
xlwings Zurich Python User Group Meetup
xlwings Zurich Python User Group Meetupxlwings Zurich Python User Group Meetup
xlwings Zurich Python User Group Meetup
 

Recently uploaded

Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...Pooja Nehwal
 
The Economic History of the U.S. Lecture 20.pdf
The Economic History of the U.S. Lecture 20.pdfThe Economic History of the U.S. Lecture 20.pdf
The Economic History of the U.S. Lecture 20.pdfGale Pooley
 
Q3 2024 Earnings Conference Call and Webcast Slides
Q3 2024 Earnings Conference Call and Webcast SlidesQ3 2024 Earnings Conference Call and Webcast Slides
Q3 2024 Earnings Conference Call and Webcast SlidesMarketing847413
 
Call US 📞 9892124323 ✅ Kurla Call Girls In Kurla ( Mumbai ) secure service
Call US 📞 9892124323 ✅ Kurla Call Girls In Kurla ( Mumbai ) secure serviceCall US 📞 9892124323 ✅ Kurla Call Girls In Kurla ( Mumbai ) secure service
Call US 📞 9892124323 ✅ Kurla Call Girls In Kurla ( Mumbai ) secure servicePooja Nehwal
 
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130Suhani Kapoor
 
Quarter 4- Module 3 Principles of Marketing
Quarter 4- Module 3 Principles of MarketingQuarter 4- Module 3 Principles of Marketing
Quarter 4- Module 3 Principles of MarketingMaristelaRamos12
 
VIP Call Girls LB Nagar ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With Room...
VIP Call Girls LB Nagar ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With Room...VIP Call Girls LB Nagar ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With Room...
VIP Call Girls LB Nagar ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With Room...Suhani Kapoor
 
Instant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School DesignsInstant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School Designsegoetzinger
 
The Economic History of the U.S. Lecture 30.pdf
The Economic History of the U.S. Lecture 30.pdfThe Economic History of the U.S. Lecture 30.pdf
The Economic History of the U.S. Lecture 30.pdfGale Pooley
 
Lundin Gold April 2024 Corporate Presentation v4.pdf
Lundin Gold April 2024 Corporate Presentation v4.pdfLundin Gold April 2024 Corporate Presentation v4.pdf
Lundin Gold April 2024 Corporate Presentation v4.pdfAdnet Communications
 
Instant Issue Debit Cards - High School Spirit
Instant Issue Debit Cards - High School SpiritInstant Issue Debit Cards - High School Spirit
Instant Issue Debit Cards - High School Spiritegoetzinger
 
Monthly Market Risk Update: April 2024 [SlideShare]
Monthly Market Risk Update: April 2024 [SlideShare]Monthly Market Risk Update: April 2024 [SlideShare]
Monthly Market Risk Update: April 2024 [SlideShare]Commonwealth
 
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
High Class Call Girls Nashik Maya 7001305949 Independent Escort Service Nashik
High Class Call Girls Nashik Maya 7001305949 Independent Escort Service NashikHigh Class Call Girls Nashik Maya 7001305949 Independent Escort Service Nashik
High Class Call Girls Nashik Maya 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779Delhi Call girls
 
Dividend Policy and Dividend Decision Theories.pptx
Dividend Policy and Dividend Decision Theories.pptxDividend Policy and Dividend Decision Theories.pptx
Dividend Policy and Dividend Decision Theories.pptxanshikagoel52
 
The Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfThe Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfGale Pooley
 
Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex
 
Vip B Aizawl Call Girls #9907093804 Contact Number Escorts Service Aizawl
Vip B Aizawl Call Girls #9907093804 Contact Number Escorts Service AizawlVip B Aizawl Call Girls #9907093804 Contact Number Escorts Service Aizawl
Vip B Aizawl Call Girls #9907093804 Contact Number Escorts Service Aizawlmakika9823
 

Recently uploaded (20)

Commercial Bank Economic Capsule - April 2024
Commercial Bank Economic Capsule - April 2024Commercial Bank Economic Capsule - April 2024
Commercial Bank Economic Capsule - April 2024
 
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
Independent Call Girl Number in Kurla Mumbai📲 Pooja Nehwal 9892124323 💞 Full ...
 
The Economic History of the U.S. Lecture 20.pdf
The Economic History of the U.S. Lecture 20.pdfThe Economic History of the U.S. Lecture 20.pdf
The Economic History of the U.S. Lecture 20.pdf
 
Q3 2024 Earnings Conference Call and Webcast Slides
Q3 2024 Earnings Conference Call and Webcast SlidesQ3 2024 Earnings Conference Call and Webcast Slides
Q3 2024 Earnings Conference Call and Webcast Slides
 
Call US 📞 9892124323 ✅ Kurla Call Girls In Kurla ( Mumbai ) secure service
Call US 📞 9892124323 ✅ Kurla Call Girls In Kurla ( Mumbai ) secure serviceCall US 📞 9892124323 ✅ Kurla Call Girls In Kurla ( Mumbai ) secure service
Call US 📞 9892124323 ✅ Kurla Call Girls In Kurla ( Mumbai ) secure service
 
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
 
Quarter 4- Module 3 Principles of Marketing
Quarter 4- Module 3 Principles of MarketingQuarter 4- Module 3 Principles of Marketing
Quarter 4- Module 3 Principles of Marketing
 
VIP Call Girls LB Nagar ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With Room...
VIP Call Girls LB Nagar ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With Room...VIP Call Girls LB Nagar ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With Room...
VIP Call Girls LB Nagar ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With Room...
 
Instant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School DesignsInstant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School Designs
 
The Economic History of the U.S. Lecture 30.pdf
The Economic History of the U.S. Lecture 30.pdfThe Economic History of the U.S. Lecture 30.pdf
The Economic History of the U.S. Lecture 30.pdf
 
Lundin Gold April 2024 Corporate Presentation v4.pdf
Lundin Gold April 2024 Corporate Presentation v4.pdfLundin Gold April 2024 Corporate Presentation v4.pdf
Lundin Gold April 2024 Corporate Presentation v4.pdf
 
Instant Issue Debit Cards - High School Spirit
Instant Issue Debit Cards - High School SpiritInstant Issue Debit Cards - High School Spirit
Instant Issue Debit Cards - High School Spirit
 
Monthly Market Risk Update: April 2024 [SlideShare]
Monthly Market Risk Update: April 2024 [SlideShare]Monthly Market Risk Update: April 2024 [SlideShare]
Monthly Market Risk Update: April 2024 [SlideShare]
 
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Maya Call 7001035870 Meet With Nagpur Escorts
 
High Class Call Girls Nashik Maya 7001305949 Independent Escort Service Nashik
High Class Call Girls Nashik Maya 7001305949 Independent Escort Service NashikHigh Class Call Girls Nashik Maya 7001305949 Independent Escort Service Nashik
High Class Call Girls Nashik Maya 7001305949 Independent Escort Service Nashik
 
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
 
Dividend Policy and Dividend Decision Theories.pptx
Dividend Policy and Dividend Decision Theories.pptxDividend Policy and Dividend Decision Theories.pptx
Dividend Policy and Dividend Decision Theories.pptx
 
The Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfThe Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdf
 
Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024
 
Vip B Aizawl Call Girls #9907093804 Contact Number Escorts Service Aizawl
Vip B Aizawl Call Girls #9907093804 Contact Number Escorts Service AizawlVip B Aizawl Call Girls #9907093804 Contact Number Escorts Service Aizawl
Vip B Aizawl Call Girls #9907093804 Contact Number Escorts Service Aizawl
 

Python. Finance. Excel. - The Thalesians

  • 1. Python. Finance. Excel. • The Thalesians, Zürich June 9th, 2016 Felix Zumstein, CFA
  • 2. About me • Consultancy: – Analytical apps for Excel & web – Professional support/training for xlwings • Previously: – 9yrs in Banking /Asset Management – Background: Finance & Economics 2
  • 3. About this talk 3 This talk is NOT about sophisticated models that make you rich. This talk is about HOW to implement classic financial models using Python and Excel. Download the material from: https://github.com/ZoomerAnalytics/talks
  • 4. Agenda 4 1) Portfolio Optimization • Intro to fundamental packages for finance • xlwings: Interactive use 2) Monte Carlo Simulation • Simulation with NumPy • xlwings: From Excel macros to web apps 3) Option Pricing and Implied Volatility • Introduction to QuantLib • xlwings: User Defined Functions (UDFs) 4) Save the Spreadsheet
  • 6. Jupyter Notebook 6 This demo gives an introduction to: • Jupyter notebook • Pandas • xlwings • Matplotlib/Seaborn • Plotly • SciPy • cvxopt
  • 7. xlwings: Basic Syntax 7 >>>  from  xlwings import  Workbook,  Range >>>  wb =  Workbook(…) >>>  Range("A1").value  =  my_variable >>>  Range("A1").options(pd.DataFrame, expand="table").value my_variable: Strings, numbers, DateTime, lists (nested), NumPy arrays, Pandas DataFrames, …
  • 8. cvxopt 8 • GPL license (SciPy: BSD) • Installation: - Mac/Linux: conda install  cvxopt - Windows: Download wheel from http://www.lfd.uci.edu/~gohlke/pythonlibs/#cvxopt then pip install it • CVXPY: Python-embedded modeling language for convex optimization problems. It wraps the solvers cvxopt, ECOS and SCS (cvxpy.org).
  • 9. 2 Monte Carlo Simulation xlwings: Excel Macros
  • 10. 10 Random walk 𝑑𝑆# =   𝜇 𝑆# 𝑑𝑡   +   𝜎 𝑆# 𝑑𝑊# In the Black-Scholes model, asset prices 𝑆# are assumed to follow a geometric Brownian motion (GBM), as defined by this stochastic differential equation (SDE): 𝜇: drift, 𝜎: volatility, 𝑊#: brownian motion Discrete time version: 𝑆# = 𝑆#+,# exp 𝜇 − 𝜎1 2 Δ𝑡   +   𝜎 𝜀# Δ𝑡 S[0,  :]  =  starting_price for t  in range(n_timesteps): rand_nums =  np.random.randn(n_simulations) S[t  + 1,  :]  =  S[t,  :]  * np.exp((mu  -­‐ 0.5  * vol ** 2)  * dt + vol * rand_nums * np.sqrt(dt)) Python: (for full context look at the repo as mentioned on slide 13)
  • 11. Same code, different front end 11 simulation.py xlwings_app.py web_app.py
  • 13. Source code and hosted app 13 Hosted Sample: www.zoomeranalytics.com/simulation-demo Source Code: https://github.com/ZoomerAnalytics/simulation-demo
  • 14. xlwings: Call Python from VBA 14 Sub MyFunction() RunPython ("import  module;module.func()") End  Sub def func(): wb =  xw.Workbook.caller() module.py VBA:
  • 15. 3 Option Pricing & Implied Volatility xlwings: UDFs
  • 16. QuantLib 16 • Open-source framework for quant finance. Released in 2000 and written in C++ with bindings for many languages. • ”Offers […] features such as market conventions, yield curve models, solvers, PDEs, Monte Carlo (low-discrepancy included), exotic options, VAR, and so on.” (quantlib.org) • Installation - Windows: Download the Python wheel from http://www.lfd.uci.edu/~gohlke/pythonlibs/#quantlib and pip-install it - Linux: apt-­‐get  install  quantlib-­‐python  quantlib-­‐swig - Mac: Err…Right now, no binaries (wheels or conda package) and building it is not exactly fun
  • 17. PyQL 17 • The official Python bindings for QuantLib (“quantlib-python”) are created with SWIG (Simplified Wrapper and Interface Generator) • Enthought started the PyQL project that uses Cython instead of SWIG. PyQL offers (from the PyQL docs): - Integration with standard datatypes (like datetime objects) and numpy arrays; - Simplified API on the Python side (e.g. usage of Handles completely hidden from the user); - Support full docstring and expose detailed function signatures to Python; - Code organised in subpackages to provide a clean namespace, very close to the C++ code organisation; - Easy extendibility thanks to Cython and shorter build time when adding new functionalities; - Sphinx documentation. • However, PyQL covers only a fraction of the official bindings.
  • 18. Options: Implied Volatility 18 Implied volatility is the volatility that makes the option price calculated by a model equal to its observed market price. 𝐶 𝐹, 𝜏 = 𝐷(𝑁 𝑑< 𝐹 − 𝑁 𝑑+ 𝐾) 𝑑± =   1 𝜎 𝜏   log 𝐹 𝐾 ± 1 2 𝜎1 𝜏 Black-Scholes formula (alternative formulation): 𝑃 𝐹, 𝜏 = 𝐷(𝑁 −𝑑+ 𝐾 − 𝑁 −𝑑< 𝐹) 𝐶, 𝑃: Call/Put Option, 𝐷: discount factor, 𝐹 = 𝑆E 𝑒 G+H I: forward price, 𝑁(J): cumulative distribution function of std normal distribution, 𝜎: volatility of returns of underlying asset, 𝐾: Strike, 𝜏: time to maturity, 𝑟: cont. comp. risk-free rate, 𝑞: dividend yield
  • 20. 4 Save the Spreadsheet xlwings: VBA unit tests
  • 21. Tough times for spreadsheet models 21 "Where a bank relies on manual processes and desktop applications (e.g. spreadsheets, databases) and has specific risk units that use these applications for software development, it should have effective mitigants in place (e.g. end-user computing policies and procedures) and other effective controls that are consistently applied across the bank's processes. " – Basel Committee on Banking Supervision, Principle 3
  • 22. Unit Tests 22 • Automated unit tests are a cornerstone of modern software development (”test-driven development”) • Excel: doesn’t offer any means to create unit tests (there’s Debug.Assert, but that doesn’t really help) • Python: has a built-in unit test module • Unit testing with xlwings is unintrusive: - No add-in to be installed - No changes to the original VBA code base - Python standard lib + xlwings is all you need • It’s a great way to verify & debug legacy VBA code
  • 23. Running VBA code with xlwings 23 xlwings has a beauuuutiful interface to access VBA Subs and Functions: VBA: Function MySum(x,  y) MySum =  x  +  y End  Function Python: >>>  wb = xw.Workbook.active() >>>  my_sum = wb.macro('MySum') >>>  my_sum(1,  2) 3
  • 24. Testing with xlwings 24 xlwings allows you to: • Unit test spreadsheets with or without VBA code • Test VBA code against an alternative implementation in Python (incl. any third party packages like SciPy or QuantLib that are usually heavily tested) Demo: Prime numbers