text stringlengths 0 4.57k |
|---|
Contents I Introducing Algorithmic Trading 1 1 Introduction to the Book............................... 3 1. 1 Introduction to Quant Start.............................. 3 1. 2 What is this Book?................................... 3 1. 3 Who is this Book For?................................. 3 1. 4 What are the Prerequis... |
2 4. 1. 1 Programming.................................. 22 4. 1. 2 Research Tools................................. 22 4. 1. 3 Event-Driven Backtesting........................... 23 4. 1. 4 Latency..................................... 23 4. 1. 5 Language Choices............................... 23 4. 1. 6 Integrated Devel... |
3 8. 1. 1 Markets..................................... 61 8. 1. 2 Instruments................................... 61 8. 1. 3 Fundamental Data............................... 62 8. 1. 4 Unstructured Data............................... 62 8. 2 Frequency of Data................................... 63 8. 2. 1 Weekly and Month... |
4 11. 4 Forecasting Stock Index Movement.......................... 103 11. 4. 1 Python Implementations............................ 103 11. 4. 2 Results..................................... 106 V Performance and Risk Management 107 12 Performance Measurement.............................. 109 12. 1 Trade Analysis........... |
5 16. 3. 1 Intraday Mean Reverting Pairs........................ 191 16. 3. 2 Parameter Adjustment............................. 191 16. 3. 3 Visualisation.................................. 194 |
6 |
Limit of Liability/Disclaimer of Warranty While the author has used their best efforts in preparing this book, they make no representations or warranties with the respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a partic... |
ii |
Part I Introducing Algorithmic Trading 1 |
Chapter 1 Introduction to the Book 1. 1 Introduction to Quant Start Quant Start was founded by Michael Halls-Moore, in 2010, to help junior quantitative analysts (QAs) find jobs in the tough economic climate. Since then the site has evolved to become a substantial resource for quantitative finance. The site now concentra... |
4 algorithms. While a deep understanding of mathematics is not absolutely necessary, it will make it easy to understand how these algorithms work on a conceptual level. If you are rusty on this material, or it is new to you, have a look at the Quant Start reading list. 1. 5 Software/Hardware Requirements Quantitative t... |
5 1. 7 What the Book does not Cover This is not a beginner book on discretionary trading, nor a book filled with “technical analysis” trading strategies. If you have not carried out any trading (discretionary or otherwise), I would suggest reading some of the books on the Quant Start reading list. It is also not a Pytho... |
6 |
Chapter 2 What Is Algorithmic Trading? Algorithmic trading, as defined here, is the use of an automated system for carrying out trades, which are executed in a pre-determined manner via an algorithm specifically without any human intervention. The latter emphasis is important. Algorithmic strategies are designed prior to... |
8 No Discretionary Input One of the primary advantages of an automated trading system is that there is (theoretically) no subsequent discretionary input. This refers to modification of trades at the point of execution or while in a position. Fear and greed can be overwhelming motivators when carrying out discretionary t... |
9 I have attempted to demonstrate a wide variety of strategies, the basis of which are nearly always grounded in a manner that is straightforward to understand. However, if you do possess numerical modelling skills then you will likely find it easier to make use of the statistical time series methods present in the Mode... |
10 usage. Libraries-The main reason to use Python is that it comes with a staggering array of libraries, which significantly reduce time to implementation and the chance of introduc-ing bugs into our code. In particular, we will make use of Num Py (vectorised operations), Sci Py (optimisation algorithms), pandas (time s... |
11 Leverage-Aretailtrader,dependingupontheirlegalsetup,isconstrainedbymargin/lever-age regulations. Private investment funds do not suffer from the same disadvantage, al-though they are equally constrained from a risk management perspective. Liquidity-Having access to a prime brokerage is out of reach of the average ret... |
12 languages such as Python or R now possess packages to construct an end-to-end backtesting, execution, risk and portfolio management system with far fewer lines-of-code (LOC) than may be needed in a more verbose language such as C++. However, this flexibility comes at a price. One either has to build the stack themsel... |
Part II Trading Systems 13 |
Chapter 3 Successful Backtesting Algorithmic backtesting requires knowledge of many areas, including psychology, mathematics, statistics, software development and market/exchange microstructure. I couldn't hope to cover all of those topics in one chapter, so I'm going to split them into two or three smaller pieces. Wha... |
16 Verification-Our strategies are often sourced externally, via our strategy pipeline. Back-testing a strategy ensures that it has not been incorrectly implemented. Although we will rarely have access to the signals generated by external strategies, we will often have access to the performance metrics such as the Sharp... |
17 Technical Bugs-Arrays/vectors in code often have iterators or index variables. Incorrect offsetsof these indices can lead to a look-ahead bias by incorporating data at N+kfor non-zerok. Parameter Calculation-Another common example of look-ahead bias occurs when calculating optimal strategy parameters, such as with li... |
18 drawdown of 25% and a maximum drawdown duration of 4 months. This would not be atypical for a momentum strategy. It is straightforward to convince oneself that it is easy to tolerate such periods of losses because the overall picture is rosy. However, in practice, it is far harder! If historical drawdowns of 25% or ... |
19 3. 3. 3 Forex Trading and ECNs The backtesting of foreign exchange strategies is somewhat trickier to implement than that of equity strategies. Forex trading occurs across multiple venues and Electronic Communication Networks (ECN). The bid/ask prices achieved on one venue can differ substantially from those on anoth... |
20 issues and improvements of milliseconds on this latency can make all the difference towards profitability. The type of strategy is also important. Momentum systems suffer more from slippage on average because they are trying to purchase instruments that are already moving in the forecast direction. The opposite is true... |
Chapter 4 Automated Execution Automated execution is the process of letting the strategy automatically generate execution signals that are the sent to the broker without any human intervention. This is the purest form of algorithmic trading strategy, as it minimises issues due to human intervention. It is the type of s... |
22 that you don't introduce bugs which can lead to biases. An example here is look-ahead bias, which Excel minimises, while a vectorised research backtester might lend itself to accidentally. Speed of Development-One shouldn't have to spend months and months implementing a backtest engine. Prototyping should only take ... |
23 4. 1. 3 Event-Driven Backtesting Once a strategy has been deemed suitable on a research basis it must be tested in a more realistic fashion. Such realism attempts to account for the majority (if not all) of the issues described in the previous chapter. The ideal situation is to be able to use the same trade generati... |
24 C++, C# and Java C++, C# and Java are all examples of general purpose object-oriented programming languages. That is, they can be used without a corresponding IDE, are all cross-platform (can be run on Windows, Mac OSX or Linux), have a wide range of libraries for nearly any imaginable task and possess have rapid ex... |
25 live execution. For our purposes, I use the term to mean any environment (often GUI-based) that isnota general purpose programming language, such as C++ or Python. MATLAB is considered an IDE, for instance. Excel While some purer quants may look down on Excel, I have found it to be extremely useful for "sanity check... |
26 Studio' provides the ability to write backtesting code as well as optimised execution algorithms and subsequently transition from a historical backtest to live paper trading. Zip Line is the Python library that powers the Quantopian service mentioned above. It is a fully event-driven backtest environment and current... |
27 I hesitate to recommend a home desktop approach to algorithmic trading. If you do decide to pursue this approach, make sure to have both a backup computer AND a backup internet connection (e. g. a 3G dongle) that you can use to close out positions under a downtime situation. 4. 2. 2 VPS The next level up from a home... |
28 |
Chapter 5 Sourcing Strategy Ideas In this chapter I want to introduce you to the methods by which I myself identify profitable algorithmic trading strategies. We will discuss how to find, evaluate and select such systems. I'll explain how identifying strategies is as much about personal preference as it is about strategy... |
30 of drawdown. If you are considering beginning with less than 10,000 USD then you will need to restrict yourself to low-frequency strategies, trading in one or two assets, as transaction costs will rapidly eat into your returns. Interactive Brokers, which is one of the friendliest brokers to those with programming sk... |
31 Financial Markets and Participants The following list details books that outline how capital markets work and describe modern electronic trading. Financial Times Guide to the Financial Markets by Glen Arnold[1]-This book is designed for the novice to the financial markets and is extremely useful for gaining insight i... |
32 However, a note of caution: Many internet trading resources rely on the concept of technical analysis. Technical analysis involves utilising basic signals analysis indicators andbehavioural psychology to determine trends or reversal patterns in asset prices. Despite being extremely popular in the overall trading spa... |
33 5. 2. 3 Journal Literature Once you have had some experience at evaluating simpler strategies, it is time to look at the more sophisticated academic offerings. Some academic journals will be difficult to access, without high subscriptions or one-off costs. If you are a member or alumnus of a university, you should be ab... |
34 By continuing to monitor the above sources on a weekly, or even daily, basis you are setting yourself up to receive a consistent list of strategies from a diverse range of sources. The next step is to determine how to reject a large subset of these strategies in order to minimise wasting your time and backtesting re... |
35 Win/Loss, Average Profit/Loss-Strategies will differ in their win/loss and average profit/loss characteristics. One can have a very profitable strategy, even if the number of losing trades exceed the number of winning trades. Momentum strategies tend to have this pattern as they rely on a small number of "big hits" in o... |
36 technical expertise. We also need to discuss the different types of available data and the different considerations that each type of data will impose on us. Let's begin by discussing the types of data available and the key issues we will need to think about, with the understanding that we will explore these issues in... |
37 recent years, but it will still require significant technical expertise to achieve in a robust manner. As can be seen, once a strategy has been identified via the pipeline it will be necessary to evaluate the availability, costs, complexity and implementation details of a particular set of historical data. You may find... |
38 |
Part III Data Platform Development 39 |
Chapter 6 Software Installation This chapter will discuss in detail how to install an algorithmic trading environment. Operating system choice is considered as a necessary first step, with the three major choices outlined. Subsequently Linux is chosen as the system of choice (Ubuntu in particular) and Python is installe... |
42 compilation process (using XCode). I have not yet successfully installed Num Py, Sci Py and pandas on my Mac Book as of this writing! However, if you can navigate the minefield that is Python installation on Mac OSX, it can provide a great environment for algorithmic research. Since the Interactive Brokers Trader Wor... |
43 6. 2. 1 Python The latest versions of Ubuntu, which at the time of writing is 13. 10, still make use of the Python 2. 7. x version family. While there is a transition underway to 3. 3. x the majority of libraries are fully compatible with the 2. 7. x branch. Thus I have chosen to use this for algorithmic trading. Th... |
44 Sci Py has now been installed. We will test it out in a similar fashion to Num Py when calculating the standard deviation of a list of integers: mhallsmoore@algobox:~$ python Python 2. 7. 4 (default, Sep 26 2013, 03:20:26) [GCC 4. 7. 3] on linux2 Type "help", "copyright", "credits" or"license" for more information. ... |
45 Now we can install matplotlib: sudo pip install matplotlib The last task of this section is to instal IPython. This is an interactive Python interpreter that provides a significantly more streamlined workflow compared to using the standard Python console. In later chapters we will emphasise the full usefulness of IPyt... |
46 The next step is to download IBPy via the 'git clone' command: cd ~/ibapi git clone https://github. com/blampe/Ib Py The final step is to enter the Ib Py directory and install using Python setuptools: cd ~/ibapi/Ib Py python setup. py. ininstall That completes the installation of IBPy. The next step is to install Tra... |
Chapter 7 Financial Data Storage In algorithmic trading the spotlight usually shines on the alpha model component of the full trading system. This component generates the trading signals, prior to filtration by a risk management and portfolio construction system. As such, algo traders often spend a significant portion of... |
48 Securities master databases often have teams of developers and data specialists ensuring high availability within a financial institution. While this is necessary in large companies, at the retail level or in a small fund a securities master can be far simpler. In fact, while large securities masters make use of expe... |
49 The advantage of flat-files are their simplicity and ability to be heavily compressed for archiv-ing or download. The main disadvantages lie in their lack of query capability and poor perfor-mance for iteration across large datasets. SQLite and Excelmitigate some of these problems by providing certain querying capabil... |
50 Price-The actual price for a particular security on a particular day. Corporate Actions-The list of all stock splits or dividend adjustments (this may lead to one or more tables), necessary for adjusting the pricing data. National Holidays-To avoid mis-classifying trading holidays as missing data errors, it can be u... |
51 7. 6 Automation The benefit of writing software scripts to carry out the download, storage and cleaning of the data is that scripts can be automated via tools provided by the operating system. In UNIX-based systems (such as Mac OSX or Linux), one can make use of the crontab, which is a continually running process tha... |
52 Onceyouhaveloggedintothe My SQLyoucancreateanewdatabasecalled securities _master and then select it: mysql> CREATE DATABASE securities _master; mysql> USE securities _master; Once you create a database it is necessary to add a new userto interact with the database. While you can use the rootuser, it is considered ba... |
53 the geographic location. It also supports a currency and a timezone offset from UTC. We also store a created and last updated date for our own internal purposes. Finally, we set the primary index key to be an auto-incrementing integer ID (which is sufficient to handle 232records): CREATE TABLE 'exchange' ( 'id' int NOT... |
54 column. Notice that the datatype is decimal(19,4). When dealing with financial data it is absolutely necessary to be precise. If we had used the floatdatatype we would end up with rounding errors due to the nature of how floatdata is stored internally. The final field stores the trading volume for the day. This uses th... |
55 Wikipedia conveniently lists the constituents of the S&P500. Note that there are actually 502 components in the S&P500! We will scrapethe website using the Python requests and Beautiful Soup libraries and then add the content directly to My SQL. Firstly make sure the libraries are installed: pip install requests pip... |
56 tds[3]. text, # Sector 'USD', now, now ) ) return symbols def insert _snp500 _symbols(symbols): """ Insert the S&P500 symbols into the My SQL database. """ # Connect to the My SQL instance db_host = 'localhost' db_user = 'sec _user' db_pass = 'password' db_name = 'securities _master' con = mdb. connect( host=db _hos... |
57 from __future __import print _function import datetime import warnings import My SQLdb as mdb import requests # Obtain a database connection to the My SQL instance db_host = 'localhost' db_user = 'sec _user' db_pass = 'password' db_name = 'securities _master' con = mdb. connect(db _host, db _user, db _pass, db _name... |
58 for yinyf_data: p = y. strip(). split(',') prices. append( (datetime. datetime. strptime(p[0], '%Y-%m-%d'), p[1], p[2], p[3], p[4], p[5], p[6]) ) except Exception as e: print ("Could not download Yahoo data: %s" % e) return prices def insert _daily _data _into _db( data _vendor _id, symbol _id, daily _data ): """ Ta... |
59 "Adding data for %s: %s out of %s" % (t[1], i+1, lentickers) ) yf_data = get _daily _historic _data _yahoo(t[1]) insert _daily _data _into _db('1', t[0], yf _data) print ("Successfully added Yahoo Finance pricing data to DB. ") Note that there are certainly ways we can optimise this procedure. If we make use of the ... |
60 2015-06-10 536. 69 2015-06-11 534. 61 2015-06-12 532. 33 2015-06-15 527. 20 This is obviously only a simple script, but it shows how powerful having a locally-stored securities master can be. It is possible to backtest certain strategies extremely rapidly with this approach, as the input/output (I/O) speed from the ... |
Chapter 8 Processing Financial Data Inthepreviouschapterweoutlinedhowtoconstructanequities-basedsecuritiesmasterdatabase. This chapter will discuss a topic that is not often considered to any great extent in the majority of trading books, that of processing financial market data prior to usage in a strategy test. Thedis... |
62 Market Instruments Equities/Indices Stock, ETFs, Futures, Options Foreign Exchange Margin/Spot, ETFs, Futures, Options Commodities Futures, Options Fixed Income Futures, Options For the purposes of this book we will concentrate almost exclusively upon equities and ETFs to simplify the implementation. 8. 1. 3 Fundame... |
63 8. 2 Frequency of Data Frequency of data is one of the most important considerations when designing an algorithmic trading system. It will impact every design decision regarding the storage of data, backtesting a strategy and executing an algorithm. Higher frequency strategies are likely to lead to more statisticall... |
64 the volumes of such data are substantial. Common storage mechanisms include HDF5, kdb and simply flat-file/CSV. Multiple limit orders at an exchange lead to the concept of an order book. This is essentially the list of all bid and ask limit orders at certain volumes for each market participant. It leads to the definiti... |
65 All of the data can be accessed by a very modern HTTP API (CSV, JSON, XML or HTML), with plugins for a wide variety of programming languages including R, Python, Matlab, Excel, Stata, Maple, C#, EViews, Java, C/C++,. NET, Clojure and Julia. Without an account 50 calls to the API are allowed per day, but this can be ... |
66 Quant Quote Quant Quoteprovidereasonablypricedhistoricalminute-, second-andtick-leveldatafor USequi-ties going back to 1998. In addition they provide institutional level real-time tick feeds, although this is of less interest to retail algorithmic traders. One of the main benefits of Quant Quote is that their data is... |
67 Notethat inpandas 0. 17. 0, pandas. io. data will be replaced by aseparate pandas-datareader package. However, for the time being (i. e. pandas versions 0. 16. x) the syntax to import the data reader is import pandas. io. data as web. In the next section we will use Quandl to create a more comprehensive, permanent d... |
68 Figure 8. 3: The Quandl authorised home page Quandl Futures Data Now click on the "New: Futures page... " link to get to the futures homepage: Figure 8. 4: The Quandl futures contracts home page For this tutorial we will be considering the highly liquid E-Mini S&P500 futures contract, which has the futures symbol ES... |
69 Figure 8. 5: E-Mini S&P500 contract page Figure 8. 6: E-Mini S&P500 historical contracts Figure 8. 7: Chart of ESZ2014 (December 2014 delivery) later usage in the Python script below. Do not share it with anyone as it is your unique au-thorisation token for Quandl downloads and is used to determine your download rat... |
70 Figure 8. 8: Download modal for ESZ2014 CSV file Downloading Quandl Futures into Python Because we are interested in using the futures data long-term as part of a wider securities master database strategy we want to store the futures data to disk. Thus we need to create a directory to hold our E-Mini contract CSV file... |
71 # March, June, September and # December delivery codes months = 'HMUZ' for yinrange(start _year, end _year+1): for minmonths: futures. append("%s%s%s" % (symbol, m, y)) return futures Nowweneedtoloopthrougheachsymbol, obtainthe CSVfilefrom Quandlforthatparticular contract and subsequently write it to disk so we can a... |
72 dl_dir = 'quandl/futures/ES' # Create the start and end years start _year = 2010 end_year = 2014 # Download the contracts into the directory download _historical _contracts( symbol, dl _dir, start _year, end _year ) # Open up a single contract via read _csv # and plot the settle price es = pd. io. parsers. read _csv... |
73 each year for US markets, and each trading day has 6. 5 hours of trading, this will equate to at least 650,000 bars of data, each with seven data points: Timestamp, Open, Low, High, Close, Volume and Open Interest. I have chosen the SPY and IWM ETFs to download to CSV. Make such to start the IQLink program in Window... |
74 data = read _historical _data _socket(sock) sock. close # Remove all the endlines and line-ending # comma delimiter from each record data = "". join(data. split("\r")) data = data. replace(",\n","\n")[:-1] # Write the data stream to disk f = open("%s. csv" % sym, "w") f. write(data) f. close() With additional subscr... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 9