MODELING FINANCIAL MARKETSUsing Visual Basic.NET and Databases to Create Pricing, Trading, and Risk Management Models BENJAMIN VAN VLIET ROBERT HENDRY McGraw-Hill New York Chicago San Fr
Trang 2Want to learn more?
We hope you enjoy this McGraw-Hill eBook! If you’d like more information about this book, its author, or related books and websites, please click here.
Trang 3MODELING FINANCIAL MARKETS
Using Visual Basic.NET and Databases
to Create Pricing, Trading, and
Risk Management Models
BENJAMIN VAN VLIET
ROBERT HENDRY
McGraw-Hill
New York Chicago San Francisco Lisbon
London Madrid Mexico City Milan
New Delhi San Juan Seoul
Singapore Sydney Toronto
Trang 4the United States of America Except as permitted under the United States Copyright Act
of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher
0-07-144288-X
The material in this eBook also appears in the print version of this title: 0-07-141772-9 All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark Where such designations appear in this book, they have been printed with initial caps
McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-hill.com or (212) 904-
4069
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc (“McGraw-Hill”) and its licensors reserve all rights in and to the work Use of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom McGraw-Hill has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or
Copyright © 2004 by The McGraw-Hill Companies, Inc All rights reserved Manufactured in
Trang 514 Introduction to Data Structures 243
iii
For more information about this title, click here.
Trang 6SECTION FOUR
16 Software Connectivity and Interoperability 271
SECTION FIVE
References 379
Acronyms 383
Index 385
Trang 7A C K N O W L E D G M E N T S
Andrew Kumiega, Nithiphong Vikitset, Anton Karadakov, DavidNorman, Keith Black, Pamela Reardon, Alex Deitz, Melanie Winter,Siriporn Treetanasawat, Mulianto The, Debbie Cernauskas,Michael Modica, Jerold Lavin, Duana Wooters, Thomas E
“Burma” Shea, Sagy Mintz, Kenneth M Horjus, Mark McCracken,Julia Spaulding, Dave Kuipers, Rich Pombonyo, Paresh Akbari,Cliff Ensing, Brain Huyser, Mark Groenenboom, Bruce Rawlings,Gary Lahey, Hank Perrit, Jack Wing, Varsha Pitre, Michael Ubis,Jason Malkin, and Irma Baines
v
Copyright © 2004 by The McGraw-Hill Companies, Inc C lick here for terms of use.
Trang 8This page intentionally left blank.
Trang 10This page intentionally left blank.
Trang 11C H A P T E R 1
Introduction
Although this book follows the layout of a programming book, theunderlying theme is financial modeling and quantitative tradingsystem development In a sense, this book really marries fourdisciplines—computer science, quantitative finance, trading strat-egy, and quality development—into one, financial engineering Thefollowing chapter, Chapter 2, outlines the Kumiega–Van VlietTrading System Development Methodology, which as you will seeprovides the underlying structure for the rest of the book As thechapters progress, we present gradually more complex program-ming ideas along with mathematics and trading applications toillustrate the steps along the Kumiega–Van Vliet paradigm So thisbook is not just about Visual Basic.NET (VB.NET) and databases It
is about modeling financial instruments in code and putting thepieces, or models, together to create an automated trading or riskmanagement system using a programming language, which in thiscase is VB.NET Let’s get started
Financial markets are in a constant state of evolution, frombuttonwood trees to trading floors to computer screens Over thelast 40 years, owing to the invention of computers and thedevelopment of quantitative tools for market analysis, the pace ofthis change has increased dramatically The revolution inderivatives market analysis really got into full swing in the early1970s when, soon after the Chicago Board Options Exchange(CBOE) began listing options on equities, Texas Instrumentsdeveloped a calculator to price options using the Black-Scholesformula (Berstein, 1996, pp 310–316) Over the coming years, onemajor outcome of this revolution may very well be a complete
3
Copyright © 2004 by The McGraw-Hill Companies, Inc C lick here for terms of use.
Trang 12automation of the trading process (Norman, 2001, p 236) In thefuture, computerized investment models and trading algorithmsand instantaneous trade execution could render human traderscompletely obsolete (Van Vliet and Kumiega, 2000).
Human traders, using strategies based on technical indicators,fundamental factors, or even plain old market savvy, are becomingincreasingly scarce More and more each day financial engineersare quantifying trading systems that can watch hundreds ofsecurities and derivatives in real time and execute hundreds ofstrategies instantaneously and simultaneously The trend thatstarted decades ago with Moore’s law (a doubling of speed incomputer processing power about every 18 months), coupled withthe decreased cost of technology and market data, means that in thefuture all profitable trading strategies may be, through mathema-tics and statistics, quantifiable and programmable
The equities trading industry caught on several years ago withprogram trading and index arbitrage, using computers to generatehundreds of orders simultaneously The options exchanges,however, have in the past prohibited automated order entry in aneffort to protect market makers But it appears now that such rulesmay very well be abolished in the near future, if they have notalready been by the time this book is published The BostonOptions Exchange (BOX), which will be opening for business inmid-2003, currently has no bylaw prohibiting automated orderentry, which will likely have the effect of forcing the other optionsexchanges to amend their rules
Whatever the future holds, however, make no mistake—thetrading game will be as it always has been: The first person, orcomputer, to recognize a profitable opportunity and execute a tradewins It’s just that being first is no longer measured in the splitseconds it takes to click your mouse button, but rather themilliseconds it takes a computer to react The financial engineerwho can program a computer to recognize profitable tradingopportunities and execute trades is really the trader of the future(Van Vliet and Kumiega, 2000)
In the trading industry, a key job performed by financialengineers, among other things, is to formalize trading strategiesbased upon quantitative research, back-test algorithms against
4 Trading System Development
Trang 13historical data, construct or supervise construction of necessarysoftware for automation of order execution, and, after implemen-tation, manage the risk of the trading system Of course, not allthese duties are always performed by just one person, but rather,usually, by a team of financial engineers and programmers.
If you intend to have a career in trading in the financialmarkets, you will likely work on such a team, which will requirethat at some point you will be required to either write computercode yourself, manage programmers, or work and interact withprogrammers on projects This will necessitate an understanding
of, at the least, Microsoft Excel spreadsheet and the Visual Basic forApplications (VBA) environment, but likely also Visual Basic.NET
or a higher-level language such as C/Cþþ or Java In addition youwill need to understand how databases are constructed andaccessed using computer code to do financial research and developtrading and risk management algorithms and systems
All financial research requires data, and the efficient ment and storage of data is crucial to the profitable operation of atrading system “Data is the lifeblood of electronic markets,” asDavid Norman states in his book Professional Electronic Trading(2002) Industrial-strength relational database management sys-tems, such as Oracle or MS SQL Server, can store gigabytes of suchthings as historical market data and firmwide trade and positioninformation (Norman, 2001) Often, historical market data is sim-ply the opening, high, low, and closing prices or other time-incremented data such as implied volatilities, but it could also bemore qualitative, economic, or fundamental data such as earningsreport data, stock splits, or Fed actions Whatever the case, analysis
manage-of data requires not only the knowledge manage-of quantitative methods,but also the programming tools to implement that analysis in a real-life environment This book addresses topics that are critical tothese aspects of trading system development
Top financial engineers estimate that only a fraction offinancial engineering actually deals with mathematics The lion’sshare of time applies to the actual construction and analysis ofmodels and forecasts and technology development
This majority of a financial engineer’s time engaged inconstruction, though, is not simply spent coding Rather, the entire
Trang 14development process requires this amount of effort; actual timespent coding should be just a part of it As you grow in yourunderstanding of programming and trading and/or risk manage-ment system development, you will become increasingly awarethat comprehensive blueprints, or plans, or development method-ologies, of a project must be laid out before any nails are hammered
or computer keys pressed The value of a development paradigmcannot be underestimated
A good methodology, though, does not mean that anengineered trading system is infallible Not every trade and notevery system makes money There are certainly dozens, if notthousands, of examples or anecdotes trotted out by “nonquant”market participants that attempt to disprove the ability ofautomated systems to outperform human traders over the longrun To be sure, the markets are “replete with examples of ‘fattails’—unusual and extreme price swings that, based on a reading
of previous prices, would have seemed implausible” according toRoger Lowenstein in his book When Genius Failed (2000, p 229) Inthe past, quantitative systems, like that of Long Term CapitalManagement, which were built on historical data have blown upquite spectacularly during financial meltdowns, or tenth standarddeviation events, when all correlations go to 1, as they say But wedon’t stop engineering bridges just because one in London felldown No matter what anybody says, using a bridge to cross a river
is still an improvement on taking a boat across Over time, withmore experience and better engineering, financial models andforecasting will improve and become more able to weather thoseonce-a-millennium floods that seem to come around every couple
of years A computer can’t beat Kasparov at chess yet But give it afew more years Our money is with Deep Blue, or Deep Junior asthe case may be, over the long haul
The real strategy for quantitative trading systems is to knowahead of time, through research, the probability of the success of aparticular trade or series of trades, and assuming the odds are inyour favor, to play as often as possible, all the while keeping a closeeye on risk and the changing trade winds (Lowenstein, 2000, p 134).Developing a profitable trading system is no small task,however One options trader we talked to estimates that it takes a
6 Trading System Development
Trang 15$10 million investment just to get in the game That $10 millionpays for building a network infrastructure, hiring high-levelquantitative analysts and programmers, and conducting at least ayear of research and development before you even make your firsttrade Much of this expense, though, may be dedicated to creatingand installing proprietary software and hardware that connects toexchanges through their application programming interfaces(APIs) APIs can be thought of as “pipelines” to the market overwhich third parties, such as exchange member trading firms, canaccess exchange data and place orders electronically Installingand maintaining a communications network for data andorder execution, however, involves a terrible tangle of inter-connecting hubs, routers, switches, and fiber optics, not to mentionconstant software redevelopment as exchanges upgrade their APIs(Norman, 2001).
Rather than incurring the time and expense it takes to buildfrom scratch, it is also possible and much less capital-intensive tolicense third-party trading software and take advantage of theexchange connections and built-in functionality for data feeds,order entry, and risk management Then proprietary analytics andtrading algorithms can be added on top of this software via theirown APIs Many of these third-party vendors have over 10 years’experience building front-end systems for futures and optionstraders and are, in terms of development, well ahead of even somemajor U.S trading houses (Norman, 2001)
In this book, we will show you how to use Visual Basic.NETand several quantitative tools to begin development of sometrading strategies and to analyze data, and we will share someideas about how to connect to industry software via APIs tomonitor financial markets and execute trades Figure 1.1 showsgraphically how to implement a trading system in this way In thisfigure the arrows represent APIs
One limitation to this architecture, however, is that nosingle front-end trading system connects to all markets around theworld So it may necessary to create proprietary software thatconnects to a multiplicity of front-end trading system APIs toprovide access to all the different markets and products (Norman,
2001, p 175)
Trang 16The term front-end trading system refers to the “clientworkstation [and software], or order entry point, on the exchangemember local area network (LAN) that a trading firm uses to accesselectronic exchange services” (Norman, 2001, p 242) An exchange
“back end” is the point where an electronic order reaches theexchange and passes through to the exchange’s matching engine(Norman, 2001, p 242) Electronically routed orders pass from afirm’s front end to the exchange back end and then, once the tradehas been executed, again to the front end as a trade-fill confirmation(Norman, 2001, p 243)
In derivatives markets, related products are often traded ondifferent markets For example, Dow futures trade on the ChicagoBoard of Trade, S&P 500 futures trade on the Chicago MercantileExchange, and S&P 500 cash options trade on the Chicago BoardOptions Exchange Shares of IBM stock trade on the NYSE and
F I G U R E 1.1
8 Trading System Development
Trang 17other stock exchanges, while IBM stock futures trade on OneChicago and NQLX and options on IBM trade on the variousoptions exchanges Given the disparate technological infrastruc-tures and trading rules for the different exchanges, connecting to all
of them for automated trading of related products can be somewhat
of a nightmare
So as you may be able to see from Figure 1.1, it is possible, forexample, to build an automatic hedging device through the type offramework we described MicroHedge is a popular institutionalsoftware package with connections to the options markets AndTrading Technologies’ X_Trader software is a popular front-endsoftware system for futures trading on electronic markets Thus, wecould create a system to trade the CBOE’s S&P 500 cash options, via
a market connection through MicroHedge’s API, that could alsoprovide real-time delta hedging with the E-Mini S&P contract onthe Chicago Mercantile Exchange via connection to TradingTechnologies’ API (Norman, 2001)
As we mentioned earlier, there are four disciplines that go intoautomated trading strategy development: computer science,quantitative finance, trading strategy, and quality development.This is a lot to learn We do not attempt teach you all of it Rather webring together some important ideas from math, technology, projectmanagement, and the financial markets that are required to build areal-world automated trading system
Trang 18This page intentionally left blank.
Trang 19C H A P T E R 2
Development Methodology
So what is an automated trading or risk management system, andwhat process do we go through to create one?
A trading or risk management system, as we define it, consists
of the rules for automated entry into and exit from a position orpositions and the technology used to make them happen Theserules are a set of logical or mathematical operations that can bebased upon qualitative, technical, or quantitative research Manybooks and papers currently available outline stock and futurestrading system development from a purely technical analysisstandpoint, often using a retail software package to optimize a set
of trading rules based upon moving averages and oscillators Inthis book, however, we will focus on quantitative analysis ofequities, equity indexes, and options on equities and theprogramming of professional, proprietary software using VisualBasic.NET
Several steps are involved in creating a quantitatively basedtrading system, and while clearly not exhaustive since there areliterally an infinite number of potential quantifiable tradingstrategies, this book presents some of the necessary steps to create
an automated system, with lots of code examples along the way.Before we begin, however, we should define the steps to go through
or the process of creating an automated system
In their paper “An Automated Trading System ment Methodology” (2003), Andrew Kumiega and Ben Van Vlietpropose a process for trading system development that consists offour phases: research and documentation of calculations, backtesting, implementation, and portfolio and risk management
Develop-11
Copyright © 2004 by The McGraw-Hill Companies, Inc C lick here for terms of use.
Trang 20KUMIEGA – VAN VLIET TRADING SYSTEM
DEVELOPMENT METHODOLOGY
By their nature, all implemented and functioning automatedtrading or risk management systems must manage two concurrentprocesses: (1) trade selection and (2) portfolio and risk manage-ment However, prior to implementation the process of develop-ment should follow a well-defined, well-documented flow of stepsalong a development methodology In 2001, Kumiega and Van Vlietfirst proposed a software development methodology for finan-cial markets that laid out the steps to codify trading and riskmanagement algorithms This earlier model is encompassed withinthis broader methodology, which outlines an entire trading systemdevelopment paradigm
Kumiega and Van Vliet propose a standardized model for thedevelopment of automated trading systems that will ensurerapidity, desired by senior management, and consistent qualitystandards, desired by financial engineers While the idiosyncrasies
of the securities and derivatives trading industries require a uniquesystem development paradigm, this methodology owes a largeportion of its structure to a combination of the traditional waterfallmodel (Royce, 1970) and the evolutionary spiral models (Boehm,1988) The combination of these two models seeks to gain fromtheir respective strengths as well as to overcome their respectiveweaknesses
Waterfall Methodology
The traditional waterfall model is a very powerful softwaredevelopment methodology and consists of four phases that, ingeneral, map to the four phases of the Kumiega–Van Vliet model—analysis, design, implementation, and ongoing system testing Atthe completion of each phase, the waterfall model requires adecision by management prior to advancing to the next phase Thisdecision is whether or not to continue development of the systembased upon the potential for profitable implementation
In a nutshell, the waterfall model forces financial engineers tothink about the system to be built and to come up with a plan forbuilding it, before they begin construction By following this model,
12 Trading System Development