SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
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?

Contenu connexe

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

In Sharjah ௵(+971)558539980 *_௵abortion pills now available.
In Sharjah ௵(+971)558539980 *_௵abortion pills now available.In Sharjah ௵(+971)558539980 *_௵abortion pills now available.
In Sharjah ௵(+971)558539980 *_௵abortion pills now available.hyt3577
 
Thane Call Girls , 07506202331 Kalyan Call Girls
Thane Call Girls , 07506202331 Kalyan Call GirlsThane Call Girls , 07506202331 Kalyan Call Girls
Thane Call Girls , 07506202331 Kalyan Call GirlsPriya Reddy
 
Kurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
Kurla Capable Call Girls ,07506202331, Sion Affordable Call GirlsKurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
Kurla Capable Call Girls ,07506202331, Sion Affordable Call GirlsPriya Reddy
 
Test bank for advanced assessment interpreting findings and formulating diffe...
Test bank for advanced assessment interpreting findings and formulating diffe...Test bank for advanced assessment interpreting findings and formulating diffe...
Test bank for advanced assessment interpreting findings and formulating diffe...robinsonayot
 
Significant AI Trends for the Financial Industry in 2024 and How to Utilize Them
Significant AI Trends for the Financial Industry in 2024 and How to Utilize ThemSignificant AI Trends for the Financial Industry in 2024 and How to Utilize Them
Significant AI Trends for the Financial Industry in 2024 and How to Utilize Them360factors
 
Bhubaneswar🌹Ravi Tailkes ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
Bhubaneswar🌹Ravi Tailkes ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...Call Girls Mumbai
 
Female Escorts Service in Hyderabad Starting with 5000/- for Savita Escorts S...
Female Escorts Service in Hyderabad Starting with 5000/- for Savita Escorts S...Female Escorts Service in Hyderabad Starting with 5000/- for Savita Escorts S...
Female Escorts Service in Hyderabad Starting with 5000/- for Savita Escorts S...kajalverma014
 
Premium Call Girls Bangalore Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
Premium Call Girls Bangalore Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...Premium Call Girls Bangalore Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
Premium Call Girls Bangalore Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...vershagrag
 
Escorts Indore Call Girls-9155612368-Vijay Nagar Decent Fantastic Call Girls ...
Escorts Indore Call Girls-9155612368-Vijay Nagar Decent Fantastic Call Girls ...Escorts Indore Call Girls-9155612368-Vijay Nagar Decent Fantastic Call Girls ...
Escorts Indore Call Girls-9155612368-Vijay Nagar Decent Fantastic Call Girls ...sanakhan51485
 
7 steps to achieve financial freedom.pdf
7 steps to achieve financial freedom.pdf7 steps to achieve financial freedom.pdf
7 steps to achieve financial freedom.pdfthemoneyacademy07
 
Bhubaneswar🌹Kalpana Mesuem ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswa...
Bhubaneswar🌹Kalpana Mesuem  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswa...Bhubaneswar🌹Kalpana Mesuem  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswa...
Bhubaneswar🌹Kalpana Mesuem ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswa...Call Girls Mumbai
 
falcon-invoice-discounting-unlocking-prime-investment-opportunities
falcon-invoice-discounting-unlocking-prime-investment-opportunitiesfalcon-invoice-discounting-unlocking-prime-investment-opportunities
falcon-invoice-discounting-unlocking-prime-investment-opportunitiesFalcon Invoice Discounting
 
Business Principles, Tools, and Techniques in Participating in Various Types...
Business Principles, Tools, and Techniques  in Participating in Various Types...Business Principles, Tools, and Techniques  in Participating in Various Types...
Business Principles, Tools, and Techniques in Participating in Various Types...jeffreytingson
 
MASTERING FOREX: STRATEGIES FOR SUCCESS.pdf
MASTERING FOREX: STRATEGIES FOR SUCCESS.pdfMASTERING FOREX: STRATEGIES FOR SUCCESS.pdf
MASTERING FOREX: STRATEGIES FOR SUCCESS.pdfCocity Enterprises
 
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...priyasharma62062
 
7 tips trading Deriv Accumulator Options
7 tips trading Deriv Accumulator Options7 tips trading Deriv Accumulator Options
7 tips trading Deriv Accumulator OptionsVince Stanzione
 
GIFT City Overview India's Gateway to Global Finance
GIFT City Overview  India's Gateway to Global FinanceGIFT City Overview  India's Gateway to Global Finance
GIFT City Overview India's Gateway to Global FinanceGaurav Kanudawala
 
Famous Kala Jadu, Black magic expert in Faisalabad and Kala ilam specialist i...
Famous Kala Jadu, Black magic expert in Faisalabad and Kala ilam specialist i...Famous Kala Jadu, Black magic expert in Faisalabad and Kala ilam specialist i...
Famous Kala Jadu, Black magic expert in Faisalabad and Kala ilam specialist i...batoole333
 

Dernier (20)

In Sharjah ௵(+971)558539980 *_௵abortion pills now available.
In Sharjah ௵(+971)558539980 *_௵abortion pills now available.In Sharjah ௵(+971)558539980 *_௵abortion pills now available.
In Sharjah ௵(+971)558539980 *_௵abortion pills now available.
 
Thane Call Girls , 07506202331 Kalyan Call Girls
Thane Call Girls , 07506202331 Kalyan Call GirlsThane Call Girls , 07506202331 Kalyan Call Girls
Thane Call Girls , 07506202331 Kalyan Call Girls
 
Kurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
Kurla Capable Call Girls ,07506202331, Sion Affordable Call GirlsKurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
Kurla Capable Call Girls ,07506202331, Sion Affordable Call Girls
 
Test bank for advanced assessment interpreting findings and formulating diffe...
Test bank for advanced assessment interpreting findings and formulating diffe...Test bank for advanced assessment interpreting findings and formulating diffe...
Test bank for advanced assessment interpreting findings and formulating diffe...
 
Significant AI Trends for the Financial Industry in 2024 and How to Utilize Them
Significant AI Trends for the Financial Industry in 2024 and How to Utilize ThemSignificant AI Trends for the Financial Industry in 2024 and How to Utilize Them
Significant AI Trends for the Financial Industry in 2024 and How to Utilize Them
 
Bhubaneswar🌹Ravi Tailkes ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...Bhubaneswar🌹Ravi Tailkes  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
Bhubaneswar🌹Ravi Tailkes ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswar ...
 
W.D. Gann Theory Complete Information.pdf
W.D. Gann Theory Complete Information.pdfW.D. Gann Theory Complete Information.pdf
W.D. Gann Theory Complete Information.pdf
 
Female Escorts Service in Hyderabad Starting with 5000/- for Savita Escorts S...
Female Escorts Service in Hyderabad Starting with 5000/- for Savita Escorts S...Female Escorts Service in Hyderabad Starting with 5000/- for Savita Escorts S...
Female Escorts Service in Hyderabad Starting with 5000/- for Savita Escorts S...
 
Premium Call Girls Bangalore Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
Premium Call Girls Bangalore Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...Premium Call Girls Bangalore Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
Premium Call Girls Bangalore Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
 
Escorts Indore Call Girls-9155612368-Vijay Nagar Decent Fantastic Call Girls ...
Escorts Indore Call Girls-9155612368-Vijay Nagar Decent Fantastic Call Girls ...Escorts Indore Call Girls-9155612368-Vijay Nagar Decent Fantastic Call Girls ...
Escorts Indore Call Girls-9155612368-Vijay Nagar Decent Fantastic Call Girls ...
 
7 steps to achieve financial freedom.pdf
7 steps to achieve financial freedom.pdf7 steps to achieve financial freedom.pdf
7 steps to achieve financial freedom.pdf
 
Bhubaneswar🌹Kalpana Mesuem ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswa...
Bhubaneswar🌹Kalpana Mesuem  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswa...Bhubaneswar🌹Kalpana Mesuem  ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswa...
Bhubaneswar🌹Kalpana Mesuem ❤CALL GIRLS 9777949614 💟 CALL GIRLS IN bhubaneswa...
 
Call Girls in Yamuna Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Yamuna Vihar  (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Yamuna Vihar  (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Yamuna Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
falcon-invoice-discounting-unlocking-prime-investment-opportunities
falcon-invoice-discounting-unlocking-prime-investment-opportunitiesfalcon-invoice-discounting-unlocking-prime-investment-opportunities
falcon-invoice-discounting-unlocking-prime-investment-opportunities
 
Business Principles, Tools, and Techniques in Participating in Various Types...
Business Principles, Tools, and Techniques  in Participating in Various Types...Business Principles, Tools, and Techniques  in Participating in Various Types...
Business Principles, Tools, and Techniques in Participating in Various Types...
 
MASTERING FOREX: STRATEGIES FOR SUCCESS.pdf
MASTERING FOREX: STRATEGIES FOR SUCCESS.pdfMASTERING FOREX: STRATEGIES FOR SUCCESS.pdf
MASTERING FOREX: STRATEGIES FOR SUCCESS.pdf
 
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
Turbhe Fantastic Escorts📞📞9833754194 Kopar Khairane Marathi Call Girls-Kopar ...
 
7 tips trading Deriv Accumulator Options
7 tips trading Deriv Accumulator Options7 tips trading Deriv Accumulator Options
7 tips trading Deriv Accumulator Options
 
GIFT City Overview India's Gateway to Global Finance
GIFT City Overview  India's Gateway to Global FinanceGIFT City Overview  India's Gateway to Global Finance
GIFT City Overview India's Gateway to Global Finance
 
Famous Kala Jadu, Black magic expert in Faisalabad and Kala ilam specialist i...
Famous Kala Jadu, Black magic expert in Faisalabad and Kala ilam specialist i...Famous Kala Jadu, Black magic expert in Faisalabad and Kala ilam specialist i...
Famous Kala Jadu, Black magic expert in Faisalabad and Kala ilam specialist i...
 

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