SlideShare a Scribd company logo
1 of 12
Succumbing to Python in the Financial Markets David Cerezo Sánchez http://cerezo.name
Python Advantages & Drawbacks Interactive, expressiveness: very quick prototyping Reduced development cycle: C++/Python=10:1 Time distribution in algorithmic trading (25% devising new strategies; 25% coding; 50% model fine-tuning and code maintenance): Python improvements impact 75% of development Free, nonproprietary (vs. Matlab, TradeStation,…) Multi-threading from Python 3.2! SEC mandating cashflow disclosure of ABS securities in Python Dynamic, not strongly typed (Java): errors at runtime!
Must-Have Python Financial Packages IbPy: Interactive Brokers Python API ultra-finance, MarWiz, pyfinancial, profitpy, QSToolKit: algorithmic trading libraries Quantlib-python: quantitative finance library NumPy, SciPy, PyIMSL: computational, scientific, numerical libraries  xlrd: extract data from .xls/.xlsx files RPy2: wrapper to R, allows R function execution within Python
Code Samples
Combo Orders with IbPy # define the contract for each leg shortContract= makeOptContract(‘MSFT', '', 26, '') longContract= makeOptContract(‘AAPL', '', 350, '') # instantiate each leg shortLeg= makeComboLeg(getConId(1,shortContract), 'SELL', 1) longLeg= makeComboLeg(getConId(2,longContract), 'BUY', 1) # build a bag with these legs calendarBagContract= makeBagContract(‘MSFT', [shortLeg, longLeg]) # build order to buy 1 spread at $0.5 buyOrder= makeOrder(‘BUY', 26, 0.5) # buy! buy! buy! con.placeOrder(nextOrderId, calendarBagContract, buyOrder) # watch the messages for a bit sleep(100)
Basket Options with Quantlib_python # Dates, risk-free rate & option parameters todaysDate = Date(8,May,2011); Settings.instance().evaluationDate = todaysDate settlementDate = Date(12,May,2011); riskFreeRate = FlatForward(settlementDate, 0.06, Actual365Fixed()) exercise = EuropeanExercise(Date(12,May,2011)); payoff = PlainVanillaPayoff(Option.Call, 10.0) # Market data underlying1 = SimpleQuote(8.0); volatility1 = BlackConstantVol(todaysDate, TARGET(), 0.12, Actual365Fixed()) dividendYield1 = FlatForward(settlementDate, 0.06, Actual365Fixed()) underlying2 = SimpleQuote(8.0); volatility2 = BlackConstantVol(todaysDate, TARGET(), 0.12, Actual365Fixed()) dividendYield2 = FlatForward(settlementDate, 0.06, Actual365Fixed()) process1 = BlackScholesMertonProcess(QuoteHandle(underlying1), YieldTermStructureHandle(dividendYield1),                                     YieldTermStructureHandle(riskFreeRate), BlackVolTermStructureHandle(volatility1)) process2 = BlackScholesMertonProcess(QuoteHandle(underlying2), YieldTermStructureHandle(dividendYield2),                                     YieldTermStructureHandle(riskFreeRate), BlackVolTermStructureHandle(volatility2)) procs = StochasticProcessVector(); procs.push_back(process1); procs.push_back(process2) matrix = Matrix(2,2); matrix[0][0] = 1.0; matrix[1][1] = 1.0; matrix[0][1] = 0.5; matrix[1][0] = 0.5 process = StochasticProcessArray(procs, matrix) basketoption = BasketOption(AverageBasketPayoff(payoff, 2), exercise) basketoption.setPricingEngine(MCEuropeanBasketEngine(process,'lowdiscrepancy ',timeSteps= 1,requiredSamples =65536)) print basketoption.NPV()
Bermuda Swaption with Quantlib_python swaptionVols = [ (Period(1, Years), Period(5, Years), 0.12), (Period(2, Years), Period(4, Years), 0.11), (Period(3, Years), Period(3, Years), 0.10),                             (Period(4, Years), Period(2, Years), 0.09), (Period(5, Years), Period(1, Years), 0.08) ] todaysDate = Date(8,May,2011); Settings.instance().evaluationDate = todaysDate; calendar = TARGET(); settlementDate = Date(12,May,2011); rate = QuoteHandle(SimpleQuote(0.05)); termStructure = YieldTermStructureHandle(FlatForward(settlementDate,rate,Actual365Fixed())) fixedLegFrequency = Annual; fixedLegTenor = Period(1,Years); fixedLegConvention = Unadjusted; floatingLegConvention = ModifiedFollowing; fixedLegDayCounter = Thirty360(Thirty360.European); floatingLegFrequency = Semiannual; floatingLegTenor = Period(6,Months) payFixed = VanillaSwap.Payer; fixingDays = 2; index = Euribor6M(termStructure); floatingLegDayCounter = index.dayCounter() swapStart = calendar.advance(settlementDate,1,Years,floatingLegConvention); swapEnd = calendar.advance(swapStart,5,Years,floatingLegConvention) fixedSchedule = Schedule(swapStart, swapEnd, fixedLegTenor, calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Forward, False) floatingSchedule = Schedule(swapStart, swapEnd, floatingLegTenor, calendar, floatingLegConvention, floatingLegConvention, DateGeneration.Forward, False) dummy = VanillaSwap(payFixed, 100.0,fixedSchedule, 0.0, fixedLegDayCounter,floatingSchedule, index, 0.0, floatingLegDayCounter) swapEngine = DiscountingSwapEngine(termStructure); dummy.setPricingEngine(swapEngine);atmRate = dummy.fairRate() atmSwap = VanillaSwap(payFixed, 1000.0,fixedSchedule, atmRate,        fixedLegDayCounter,floatingSchedule, index, 0.0,floatingLegDayCounter) otmSwap = VanillaSwap(payFixed, 1000.0,fixedSchedule, atmRate*1.4, fixedLegDayCounter,floatingSchedule, index, 0.0,floatingLegDayCounter) itmSwap =  VanillaSwap(payFixed, 1000.0,fixedSchedule, atmRate*0.6, fixedLegDayCounter,floatingSchedule, index, 0.0,floatingLegDayCounter) atmSwap.setPricingEngine(swapEngine);otmSwap.setPricingEngine(swapEngine);itmSwap.setPricingEngine(swapEngine) helpers = [ SwaptionHelper(maturity, length,QuoteHandle(SimpleQuote(vol)),index, index.tenor(), index.dayCounter(),index.dayCounter(), termStructure)                        for maturity, length, vol in swaptionVols ] times = dict([(t,1) for t in h.times() for h in helpers]) times = times.keys(); times.sort(); grid = TimeGrid(times, 30); BKmodel = BlackKarasinski(termStructure) for h in helpers:     h.setPricingEngine(TreeSwaptionEngine(BKmodel,grid)) calibrate(BKmodel, helpers, 0.05);bermudanDates = [ d for d in fixedSchedule ][:-1]; exercise = BermudanExercise(bermudanDates) atmSwaption = Swaption(atmSwap, exercise);otmSwaption = Swaption(otmSwap, exercise);itmSwaption = Swaption(itmSwap, exercise) tse=TreeSwaptionEngine(BKmodel, 50); atmSwaption.setPricingEngine(tse);otmSwaption.setPricingEngine(tse);itmSwaption.setPricingEngine(tse) print ('Black-Karasinski numerical', itmSwaption.NPV(), atmSwaption.NPV(), otmSwaption.NPV())
Fast implementation Investment Strategies “Portable Alphas from Pension Mispricing”, Journal of Portfolio Management, Summer 2006, 44-53 Pure alpha strategy 1.51% (monthly), S=0.26 Just 200 lines of Python: Heavy use of map, reduce, filter, lambda SciPy: OLS scikits.timeseries Easier to implement using RPy2 (R wrapper)
What lies ahead…
Substitutes vs Complements Paradox Quant/algo trading focused at human trader substitution, but… Moravec’s Paradox: Computer’s excel where humans are weak, and vice versa  Vg. Advanced Chess (Computer-Augmented Chess Playing): computer chess programs allowed at human competitions Computers better at brute-force position evaluation, opening and endgame databases, transposition and refutation tables…  Respect human common sense and judgment Promoted by top players: Kasparov, Anand, Topalov, … Computer-assisted Playchess.com Freestyle Chess 2005 Tournament: Amateurs+computers+better process >> specialized chess supercomputers >> grandmasters+computer+inferior process
Backtesting vs. Forward Testing Why do people love backtesting so much?  overfitted model calibrations will always prove their strategies to have very high alpha&Sharpe ratio With hindsight, everyone’s a winner In HFT/algo/quant trading, forward testing should be the golden standard: Extremely fast changing market conditions Reverse-engineered strategies that stop working
Market Microstructure Don’t forget about optimal execution sizes! Or expected trading costs given trading volume and volatility!

More Related Content

What's hot (10)

Encoder + decoder
Encoder + decoderEncoder + decoder
Encoder + decoder
 
Applying Linear Optimization Using GLPK
Applying Linear Optimization Using GLPKApplying Linear Optimization Using GLPK
Applying Linear Optimization Using GLPK
 
C++ amp on linux
C++ amp on linuxC++ amp on linux
C++ amp on linux
 
OPTEX Mathematical Modeling and Management System
OPTEX Mathematical Modeling and Management SystemOPTEX Mathematical Modeling and Management System
OPTEX Mathematical Modeling and Management System
 
Practice Exercise Set 1
Practice Exercise Set 1Practice Exercise Set 1
Practice Exercise Set 1
 
Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014
 
662305 LAB13
662305 LAB13662305 LAB13
662305 LAB13
 
Fast Wavelet Tree Construction in Practice
Fast Wavelet Tree Construction in PracticeFast Wavelet Tree Construction in Practice
Fast Wavelet Tree Construction in Practice
 
Fast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group TestingFast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group Testing
 
Advance java
Advance javaAdvance java
Advance java
 

Viewers also liked

Rethink db with Python
Rethink db with PythonRethink db with Python
Rethink db with Python
Prabhu Raghav
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1
AkramWaseem
 
MySQL User Conference 2009: Python and MySQL
MySQL User Conference 2009: Python and MySQLMySQL User Conference 2009: Python and MySQL
MySQL User Conference 2009: Python and MySQL
Ted Leung
 

Viewers also liked (18)

Rethink db with Python
Rethink db with PythonRethink db with Python
Rethink db with Python
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
 
MySQL User Conference 2009: Python and MySQL
MySQL User Conference 2009: Python and MySQLMySQL User Conference 2009: Python and MySQL
MySQL User Conference 2009: Python and MySQL
 
Scaling mysql with python (and Docker).
Scaling mysql with python (and Docker).Scaling mysql with python (and Docker).
Scaling mysql with python (and Docker).
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
 
Python for Derivative Analytics
Python for Derivative AnalyticsPython for Derivative Analytics
Python for Derivative Analytics
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL Databases
 
PostgreSQLとPythonとSQL
PostgreSQLとPythonとSQLPostgreSQLとPythonとSQL
PostgreSQLとPythonとSQL
 
Python for Big Data Analytics
Python for Big Data AnalyticsPython for Big Data Analytics
Python for Big Data Analytics
 
Python for Big Data Analytics
Python for Big Data AnalyticsPython for Big Data Analytics
Python for Big Data Analytics
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLTen Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
 
Python PPT
Python PPTPython PPT
Python PPT
 
Orchestrating Docker containers at scale
Orchestrating Docker containers at scaleOrchestrating Docker containers at scale
Orchestrating Docker containers at scale
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
FOLLY
FOLLYFOLLY
FOLLY
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similar to Succumbing to the Python in Financial Markets

Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)
Cdiscount
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트
기룡 남
 

Similar to Succumbing to the Python in Financial Markets (20)

Where the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-OptimisationsWhere the wild things are - Benchmarking and Micro-Optimisations
Where the wild things are - Benchmarking and Micro-Optimisations
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Quality Python Homework Help
Quality Python Homework HelpQuality Python Homework Help
Quality Python Homework Help
 
Python Software Testing in Kytos.io
Python Software Testing in Kytos.ioPython Software Testing in Kytos.io
Python Software Testing in Kytos.io
 
ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine
 
Java agents are watching your ByteCode
Java agents are watching your ByteCodeJava agents are watching your ByteCode
Java agents are watching your ByteCode
 
R/Finance 2009 Chicago
R/Finance 2009 ChicagoR/Finance 2009 Chicago
R/Finance 2009 Chicago
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)"Используем MetricKit в бою" / Марина Звягина (Vivid Money)
"Используем MetricKit в бою" / Марина Звягина (Vivid Money)
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
Monitoring Complex Systems: Keeping Your Head on Straight in a Hard World
Monitoring Complex Systems: Keeping Your Head on Straight in a Hard WorldMonitoring Complex Systems: Keeping Your Head on Straight in a Hard World
Monitoring Complex Systems: Keeping Your Head on Straight in a Hard World
 
Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트
 
Introduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimizationIntroduction to cython: example of GCoptimization
Introduction to cython: example of GCoptimization
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
Машинное обучение на JS. С чего начать и куда идти | Odessa Frontend Meetup #12
Машинное обучение на JS. С чего начать и куда идти | Odessa Frontend Meetup #12Машинное обучение на JS. С чего начать и куда идти | Odessa Frontend Meetup #12
Машинное обучение на JS. С чего начать и куда идти | Odessa Frontend Meetup #12
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
NTU ML TENSORFLOW
NTU ML TENSORFLOWNTU ML TENSORFLOW
NTU ML TENSORFLOW
 
Xgboost
XgboostXgboost
Xgboost
 
Bluespec @waseda
Bluespec @wasedaBluespec @waseda
Bluespec @waseda
 

Recently uploaded

Recently uploaded (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Succumbing to the Python in Financial Markets

  • 1. Succumbing to Python in the Financial Markets David Cerezo Sánchez http://cerezo.name
  • 2. Python Advantages & Drawbacks Interactive, expressiveness: very quick prototyping Reduced development cycle: C++/Python=10:1 Time distribution in algorithmic trading (25% devising new strategies; 25% coding; 50% model fine-tuning and code maintenance): Python improvements impact 75% of development Free, nonproprietary (vs. Matlab, TradeStation,…) Multi-threading from Python 3.2! SEC mandating cashflow disclosure of ABS securities in Python Dynamic, not strongly typed (Java): errors at runtime!
  • 3. Must-Have Python Financial Packages IbPy: Interactive Brokers Python API ultra-finance, MarWiz, pyfinancial, profitpy, QSToolKit: algorithmic trading libraries Quantlib-python: quantitative finance library NumPy, SciPy, PyIMSL: computational, scientific, numerical libraries xlrd: extract data from .xls/.xlsx files RPy2: wrapper to R, allows R function execution within Python
  • 5. Combo Orders with IbPy # define the contract for each leg shortContract= makeOptContract(‘MSFT', '', 26, '') longContract= makeOptContract(‘AAPL', '', 350, '') # instantiate each leg shortLeg= makeComboLeg(getConId(1,shortContract), 'SELL', 1) longLeg= makeComboLeg(getConId(2,longContract), 'BUY', 1) # build a bag with these legs calendarBagContract= makeBagContract(‘MSFT', [shortLeg, longLeg]) # build order to buy 1 spread at $0.5 buyOrder= makeOrder(‘BUY', 26, 0.5) # buy! buy! buy! con.placeOrder(nextOrderId, calendarBagContract, buyOrder) # watch the messages for a bit sleep(100)
  • 6. Basket Options with Quantlib_python # Dates, risk-free rate & option parameters todaysDate = Date(8,May,2011); Settings.instance().evaluationDate = todaysDate settlementDate = Date(12,May,2011); riskFreeRate = FlatForward(settlementDate, 0.06, Actual365Fixed()) exercise = EuropeanExercise(Date(12,May,2011)); payoff = PlainVanillaPayoff(Option.Call, 10.0) # Market data underlying1 = SimpleQuote(8.0); volatility1 = BlackConstantVol(todaysDate, TARGET(), 0.12, Actual365Fixed()) dividendYield1 = FlatForward(settlementDate, 0.06, Actual365Fixed()) underlying2 = SimpleQuote(8.0); volatility2 = BlackConstantVol(todaysDate, TARGET(), 0.12, Actual365Fixed()) dividendYield2 = FlatForward(settlementDate, 0.06, Actual365Fixed()) process1 = BlackScholesMertonProcess(QuoteHandle(underlying1), YieldTermStructureHandle(dividendYield1), YieldTermStructureHandle(riskFreeRate), BlackVolTermStructureHandle(volatility1)) process2 = BlackScholesMertonProcess(QuoteHandle(underlying2), YieldTermStructureHandle(dividendYield2), YieldTermStructureHandle(riskFreeRate), BlackVolTermStructureHandle(volatility2)) procs = StochasticProcessVector(); procs.push_back(process1); procs.push_back(process2) matrix = Matrix(2,2); matrix[0][0] = 1.0; matrix[1][1] = 1.0; matrix[0][1] = 0.5; matrix[1][0] = 0.5 process = StochasticProcessArray(procs, matrix) basketoption = BasketOption(AverageBasketPayoff(payoff, 2), exercise) basketoption.setPricingEngine(MCEuropeanBasketEngine(process,'lowdiscrepancy ',timeSteps= 1,requiredSamples =65536)) print basketoption.NPV()
  • 7. Bermuda Swaption with Quantlib_python swaptionVols = [ (Period(1, Years), Period(5, Years), 0.12), (Period(2, Years), Period(4, Years), 0.11), (Period(3, Years), Period(3, Years), 0.10), (Period(4, Years), Period(2, Years), 0.09), (Period(5, Years), Period(1, Years), 0.08) ] todaysDate = Date(8,May,2011); Settings.instance().evaluationDate = todaysDate; calendar = TARGET(); settlementDate = Date(12,May,2011); rate = QuoteHandle(SimpleQuote(0.05)); termStructure = YieldTermStructureHandle(FlatForward(settlementDate,rate,Actual365Fixed())) fixedLegFrequency = Annual; fixedLegTenor = Period(1,Years); fixedLegConvention = Unadjusted; floatingLegConvention = ModifiedFollowing; fixedLegDayCounter = Thirty360(Thirty360.European); floatingLegFrequency = Semiannual; floatingLegTenor = Period(6,Months) payFixed = VanillaSwap.Payer; fixingDays = 2; index = Euribor6M(termStructure); floatingLegDayCounter = index.dayCounter() swapStart = calendar.advance(settlementDate,1,Years,floatingLegConvention); swapEnd = calendar.advance(swapStart,5,Years,floatingLegConvention) fixedSchedule = Schedule(swapStart, swapEnd, fixedLegTenor, calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Forward, False) floatingSchedule = Schedule(swapStart, swapEnd, floatingLegTenor, calendar, floatingLegConvention, floatingLegConvention, DateGeneration.Forward, False) dummy = VanillaSwap(payFixed, 100.0,fixedSchedule, 0.0, fixedLegDayCounter,floatingSchedule, index, 0.0, floatingLegDayCounter) swapEngine = DiscountingSwapEngine(termStructure); dummy.setPricingEngine(swapEngine);atmRate = dummy.fairRate() atmSwap = VanillaSwap(payFixed, 1000.0,fixedSchedule, atmRate, fixedLegDayCounter,floatingSchedule, index, 0.0,floatingLegDayCounter) otmSwap = VanillaSwap(payFixed, 1000.0,fixedSchedule, atmRate*1.4, fixedLegDayCounter,floatingSchedule, index, 0.0,floatingLegDayCounter) itmSwap = VanillaSwap(payFixed, 1000.0,fixedSchedule, atmRate*0.6, fixedLegDayCounter,floatingSchedule, index, 0.0,floatingLegDayCounter) atmSwap.setPricingEngine(swapEngine);otmSwap.setPricingEngine(swapEngine);itmSwap.setPricingEngine(swapEngine) helpers = [ SwaptionHelper(maturity, length,QuoteHandle(SimpleQuote(vol)),index, index.tenor(), index.dayCounter(),index.dayCounter(), termStructure) for maturity, length, vol in swaptionVols ] times = dict([(t,1) for t in h.times() for h in helpers]) times = times.keys(); times.sort(); grid = TimeGrid(times, 30); BKmodel = BlackKarasinski(termStructure) for h in helpers: h.setPricingEngine(TreeSwaptionEngine(BKmodel,grid)) calibrate(BKmodel, helpers, 0.05);bermudanDates = [ d for d in fixedSchedule ][:-1]; exercise = BermudanExercise(bermudanDates) atmSwaption = Swaption(atmSwap, exercise);otmSwaption = Swaption(otmSwap, exercise);itmSwaption = Swaption(itmSwap, exercise) tse=TreeSwaptionEngine(BKmodel, 50); atmSwaption.setPricingEngine(tse);otmSwaption.setPricingEngine(tse);itmSwaption.setPricingEngine(tse) print ('Black-Karasinski numerical', itmSwaption.NPV(), atmSwaption.NPV(), otmSwaption.NPV())
  • 8. Fast implementation Investment Strategies “Portable Alphas from Pension Mispricing”, Journal of Portfolio Management, Summer 2006, 44-53 Pure alpha strategy 1.51% (monthly), S=0.26 Just 200 lines of Python: Heavy use of map, reduce, filter, lambda SciPy: OLS scikits.timeseries Easier to implement using RPy2 (R wrapper)
  • 10. Substitutes vs Complements Paradox Quant/algo trading focused at human trader substitution, but… Moravec’s Paradox: Computer’s excel where humans are weak, and vice versa Vg. Advanced Chess (Computer-Augmented Chess Playing): computer chess programs allowed at human competitions Computers better at brute-force position evaluation, opening and endgame databases, transposition and refutation tables… Respect human common sense and judgment Promoted by top players: Kasparov, Anand, Topalov, … Computer-assisted Playchess.com Freestyle Chess 2005 Tournament: Amateurs+computers+better process >> specialized chess supercomputers >> grandmasters+computer+inferior process
  • 11. Backtesting vs. Forward Testing Why do people love backtesting so much? overfitted model calibrations will always prove their strategies to have very high alpha&Sharpe ratio With hindsight, everyone’s a winner In HFT/algo/quant trading, forward testing should be the golden standard: Extremely fast changing market conditions Reverse-engineered strategies that stop working
  • 12. Market Microstructure Don’t forget about optimal execution sizes! Or expected trading costs given trading volume and volatility!