Tuesday, December 27, 2011

Risk indicators

During the financial crisis of 2008, I wrote about how I watched some risk indicators such as the VIX or the TED spread  to decide what leverage I should use for my trading strategies. It turns out that this procedure is just as critical for the current crisis that began in August 2011. In fact, more than leverage-determinants, they can be used as the all-important variable that determines whether a certain strategy should be run at all. (What's the point of running a model that you think will lose money with low leverage?)


There are now more than a few of these risk indicators to pick from. Besides the VIX and the TED, there are the VSTOXX (EURO STOXX 50 Volatility), the VXY (JPMorgan G7 Volatility Index), the EM-VXY (JPMorgan Emerging Market Volatility Index), the ETF's ONN and OFF, and probably many more that I haven't heard of yet. 


A lot of academic research has been done on whether we can devise "regime switching" models based on some complicated pattern-recognition algorithms to decide whether a market is in a certain "regime" which favors this or that particular model or parameter set. And often, these regime switching models rely on the recognition of some complicated set of patterns in the historical price series. Sorry to say, I have not found any of these complex regime switching model to have any real out-of-sample predictive power. On the other hand, my research shows that some of the aforementioned simple risk indicators will indeed prevent some trading models from falling off the cliff.


But which of these indicators are applicable to which model? This is not so obvious. For example, you might think that the EM-VXY would be an ideal leading indicator for Forex trading models that involve emerging market currencies, but I have found that it is only a contemporaneous (and thus useless) indicator to mine. Another example, I said during the 2008 financial crisis that VIX seems to be a useless contemporaneous indicator for equities trading models, but strangely, it is a good leading indicator for FX models. In contrast, the TED spread that everyone were obsessed about in 2008 shot up to over 300 bps then, but never went beyond 100 bps this time around. So really only rigorous backtesting can guide us here.


What risk indicators do you use? And have you really backtested their efficacies? Your comments would be very welcome here.

Friday, November 11, 2011

Trading platform and EC2 revisited

Recently I opened a discussion on the various software platforms which allow the programmers among us to build trading strategies easily. Here is one other addition: Quantopian. It is only in alpha stage, but I did get a preview of its features:

1) You can code in Python, which is an easier language to learn than Java, but no less powerful. In fact, I know of a superb programmer who uses Python to backtest HF strategies.

2) It is web-based, which means you can take advantage of collocation on a server much more stable than your own desktops. (For those who worry about the confidentiality of your strategies, the founder indicated to me that they can run an image of the software on an Amazon EC2 account that you owned so they won't have access to your codes. As for the confidentiality of codes residing on EC2 itself, please see below*.)

3) It is event-driven (or for those who like the latest jargon: CEP-enabled), like all the Java API's that I discussed in the previous article.

4) They have 1-min US equities data for backtesting. Tick-level data will be available soon.

5) Toolboxes for common technical indicators, mathematical algorithms, etc. will be available soon.

6) They will run a competition for trading models which makes it easier for independent traders to become trading advisers to others, or to raise money for their own funds.

Unfortunately, live walk-forward testing is not yet available.

* Some readers have wondered whether it is safe to run their trading models on Amazon's EC2. Won't Amazon's employees have access to their wildly profitable strategies? The answer is no: Amazon's security policy:


Guest Operating System: Virtual instances are completely controlled by the customer. Customers have full root access 
or administrative control over accounts, services, and applications. AWS does not have any access rights to customer 
instances and cannot log into the guest OS....

Thanks to a reader OL from France who provided me with this info. He also told me that: 

"So, I finally deployed my momentum strategy on a Linux instance of EC2 (which is free btw).
I wrote it based on the java demo application provided by Interactive Brokers and some parts of Algoquant.
So far, I use a European instance of EC2 which alas doesn't have the best latency to IB US servers (90 ms) but still better than my bedroom connection. 
A test ping from a US instance to IB US servers results in only 15 ms ..."

So there you go: Java+Algoquant+IB+EC2=profit.

Friday, September 30, 2011

Stop loss, profit cap, survivorship bias, and black swans

I have long espoused the view that we should not impose stop-losses on mean-reverting strategies, nor profit caps on momentum strategies. My view on the latter has not changed, but it has evolved on the former.

My original reason for opposing stop-losses on mean-reverting strategy is this. Say you believe your specific price series is mean-reverting, and say you have entered into a long position when the price is low. Now, however, the price gets much lower, and you are suffering a large unrealized loss. Well, based on your mean-reverting belief, you should buy more instead of liquidating! Indeed, if you backtest the effect of stop-losses on mean-reverting strategies, you will almost inevitably find that they decrease the overall returns and even Sharpe ratios.

But what this simplistic view ignored is 1) survivorship bias, and 2) black swan events. (Hat tip: Ben, who prompted me to consider these two issues.)

1) We normally would only trade those price series with a mean-reverting strategy only if we see that the prices did eventually revert. No one would bother to trade those price series that used to mean-revert, but suddenly stopped doing so. But saying that stop-losses are harmful to mean-reverting strategies is ignoring the fact that some mean-reverting will stop working altogether and would not survive our strategies selection process.

2) Let's define black swan events as those that did not occur in your backtest period. For example, let's say you never had a loss of 20% in a single day. So if you backtest a stop-loss of 20%, it will have no effect whatsoever on your backtest performance. However, no one can say for sure that it won't occur in the future. So if you or your investors simply cannot tolerate a 20% loss, you should impose this as a stop-loss. (After all, your brokerage has already imposed a stop-loss of 100% on you whether you like it or not.)

We can in fact turn point 2) around when deciding what stop-loss to use: a stop-loss should be loose enough so that it should have no effect on the backtest performance, and of course tight enough so that it will not result in the demise of your trading career.

There is also the issue of whether to use stop-loss on the intraday drawdown, or to use it on the multiple-day drawdown. I would argue that only intraday stop-loss is important to prevent a black-swan loss. In practice, when a strategy has a string of non-catastrophic losses occurring over multiple days, resulting in a large, unprecedented, drawdown, the trader will typically re-examine the strategy, taking into account this most recent performance and tweak the strategy so that it could theoretically be avoided. This is almost like a multi-day stop-loss strategy, as we stop an old strategy and start a new, modified, one. (Though the modified strategy might still recommend that you keep holding the current position!)

Now why am I still holding dear to the principle that one should not impose profit-caps on momentum strategies? Why, the possibility of black swan events again! But this time, any black swan can only result in unprecedented one-day gain instead of loss, since we should always have stop-losses on momentum strategies. We certainly don't want to impose a profit-cap to rule out this possibility!

Sunday, September 18, 2011

More on automated trading platforms

The ideal software platform for automating backtesting and executing your algorithmic trading strategies depends mainly on your level of programming expertise and your budget. If you are a competent programmer in, say, Java or C#, there is nothing to prevent you from utilizing the API offered (usually for free) by many brokerages to automate execution. And of course, it is also easy for you to write a separate backtesting program utilizing historical data. However, even for programmer-traders, there are a couple of inconveniences in developing these programs from scratch:

A) Every time we change brokerages, we have to re-write parts of the low-level functions that utilize the brokerage's API;

B) The automated trading program cannot be used to backtest unless a simulator is built to feed the historical data into the program as if they were live. To reduce bugs, it is better to have the same code that both backtests and trades live.

This is where a number of open-source algorithmic trading development platforms come in. These platforms all assume that the user is a Java programmer. But they eliminate the hassles A) and B) above as they serve as the layer that shield you from the details of the brokerage's API, and let you go from backtesting to live trading mode with a figurative turn of a key. I have taken a tour of one such platforms Marketcetera, and will highlight some features here:

1) It has a trading GUI with features similar to that of IB's TWS. This will be useful if your own brokerage's GUI is dysfunctional.

2) Complex Event Processing (CEP) is available as a module. CEP is essentially a way for you to easily specify what kind of market/pricing events should trigger a trading action. For e.g., "BUY if ask price is below 20-min moving average." Of course, you could have written this trading rule in a callback function, but to retrieve the 20-min MA on-demand could be quite messy. CEP solves that data retrieval problem for you by storing only those data that is needed by your registered trading rules.

3) It can use either FIX or a brokerage's API for connection. Available brokerage connectors include Interactive Brokers and Lime Brokerage.

4) It offers a news feed, which can be used by your trading algorithms to trigger trading actions if you use Java's string processing utilities to parse the stories properly.

5) The monthly cost ranges from $3,500 - $4,500.

If Marketcera is beyond your budget, you can check out AlgoTrader. It has advantages 1)-3) but not 4) listed above, and is completely free. I invite readers who have tried these or other similar automated trading platforms to comment their user experience here.

P.S. For those of us who use Matlab to automate our executions, a reader pointed out there is a new product MATTICK that allows you to send order via the FIX protocol which should let us trade with a great variety of brokerages.

Saturday, July 23, 2011

Sorry, your return is too high for us

I enjoyed reading Richard Wilson's The Hedge Fund Book (Richard also runs the Hedge Fund Blogger site). To be clear: it is purely marketing-oriented. It doesn't tell you how to find a successful trading strategy, but its focus is to tell you how to market your fund to investors once you have a successful strategy. To that end, it does a pretty good job in conveying what might be conventional wisdom to seasoned fund managers. (For e.g., don't bother to market to institutional investors if your AUM is less than $100M.) The book is filled with quite engaging interviews with fund managers, fund marketers, and other fund service providers (including our very own administrator Fund Associates). If Scott Patterson's The Quants is about the gods of hedge funds, this book is for and about the mortals.

One paragraph in the book stood out: "I've worked closely on the third-party marketing and capital introduction/prime brokerage side of the business, and I often see both types of firms deny clients service [to funds with high returns and high risk] ... Nobody wants to be associated with a manager aiming at 30 percent a month returns."

Maybe not aiming at, but what's wrong with achieving a 30 percent a month returns? I have actually met institutional investors who don't want to look at a fund that actually achieved double-digit monthly returns. Presumably that's because they believe that a high return automatically implies high risk, and also presumably a high leverage as well.  I would argue that there are 2 reasons not to completely dismiss such funds out-of-hand:

1) Leverage should not be determined arbitrarily, but should be based on the minimum of what's dictated by half-Kelly (see my extensive discussions of Kelly formula on this blog and in my book) and what's dictated by the maximum single-day drawdown seen historically or in VaR simulations. And if this minimum still turns out to be higher than what most institutional investors are comfortable with, one should be bold enough to adopt it in your fund.

2) As an investor, there is an easy way to control leverage and risk: just apply Constant Proportion Portfolio Insurance (a concept also discussed elsewhere on this blog). For example, if the fund manager tells you the fund employs a constant 10x leverage (as dictated by the risk analysis outlined in 1) and you are only comfortable with 5x leverage, just invest half your capital into the fund, and keep the other half as cash in your bank account! Going forward, if the fund loses money, your effective leverage would have decreased to below 5x. Say you invested $1M into the fund, and kept $1M in the bank. And say the fund lost $0.5M. Your total equity is now $1.5M, and the fund manager is supposed to trade a $0.5M*10=$5M portfolio. Your effective leverage is now only 3.33x, well within your tolerance. Now if instead, the fund made money, you can immediately withdraw some of the profits to keep your effective leverage at 5x. So, say the fund made $0.5M. Your equity is now $2.5M, and the fund manager is supposed to trade a $1.5M*10=$15M portfolio. If you don't withdraw, this would increase your effective leverage to 6x. But if you immediately withdraw $0.25M, then the fund manager will trade a $1.25M*10=$12.5M portfolio, giving you an effective leverage of the desired 5x.

If you are an investor in hedge funds, please let us know what you think of this scheme in the comments section!

Monday, July 18, 2011

The social utility of hedge funds

There is an article in the New Yorker magazine profiling Bridgewater Associates, the world's biggest global macro hedge fund. Inevitably, we come to the awkward question: "If hedge-fund managers are playing a zero-sum game, what is their social utility?"


I thought about this question a lot in the past, and I used to agree with many others that the social utility of hedge funds, or trading in general, is to provide liquidity to the markets. And a good economic case can be made that the more liquid a market is, the higher the utility it is to all participants. However, based on recent experience of flash crash and other unfortunate mishaps, we find out that traders typically do not provide liquidity when it is needed most! So this answer becomes quite unsatisfactory.


In trying to come up with a better reply, I though it is curious that few people asked "What is the purpose of having a Department of Defence?" since wars between nations are typically also zero-sum games, yet we greatly honour those who serve in the armed forces (in contrast to our feelings for hedge fund managers).


To me, clearly the answer with the best moral justification is that, in both cases, there is great social utility in defending either your clients' comfortable retirement from financial meltdown (e.g. due to governmental or corporate mismanagement), or in defending your country from foreign aggression. More specifically, the purpose of hedge funds is to reduce long-term volatility in your clients' net worth. (I would like to say "reduce risks to your clients' net worth", but that would be a bit too optimistic!) 


I emphasize long-term volatility, because of course trading generates a lot of daily or hourly volatility in your clients' equity. But I do not believe that such short-term volatility affects ones' life goals. On the other hand, a 3-or-more-year drawdown in a typical buy-and-hold portfolio can wreck havoc with many lives.

If one day, the markets become so quiescent that few hedge funds can generate higher Sharpe ratio than a buy-and-hold portfolio (as indeed seems to be the case with the US equities markets these days), then yes, most hedge fund managers should just quit, instead of hogging intellectual resources from our best universities.

Sunday, July 03, 2011

Hedge fund transparency and "barometers"

Jim Liew of Alpha Quant Club recently posted an interesting article about the increasing demand for transparency of hedge fund strategies by institutional investors, so much so that they are essentially willing to invest only in managed accounts with real-time trades and positions updates. This is, of course, bad for fund managers, since not only can the investor reverse-engineer the simpler strategies from such knowledge, they can also piggy-back on the trades, thus paying a much smaller portion of their profits as performance fee. One might be tempted to think that since the investors are going to reverse-engineer the product anyway, why not just make it as simple and as generic as possible, and charge a much lower fee than the usual 2-20 (which hopefully will attract a much larger investor base), so that the main value to the investor is just convenience and not the originality of the strategy?

In fact, Jim wants to do just that. He proposes to construct hedge fund "barometers", essentially prototypical hedge fund strategies running in managed accounts. This would work well if these barometers have large enough capacities such that the performance can hold up even when a large number of investors sign up. From the investors' point of view, this is a trade-off between investing in a truly outstanding, high-performance strategy while paying a large fee and losing "transparency", versus just investing in a generic strategy that may still outperform the broad market. For some institutional investors, this might just be the bargain they are looking for.

Friday, June 17, 2011

When cointegration of a pair breaks down

I have written a lot in the past about the cointegration of ETF pairs, and how this condition can lead to profitable pairs trading. However, as every investment advisor could have told you, past cointegration is no guarantee of future cointegration. Often, cointegration for a pair breaks down for an extended period, maybe as long as a half a year or more. Naturally, trading this pair during this period is a losing proposition, but abandoning such a pair completely is also unsatisfactory, since cointegration often mysteriously returns after a while.

A case in point is the ETF pair GLD-GDX. When I first tested it in 2006, it was an excellent candidate for pair trading, and I not only traded it in my personal portfolio, but we traded it in our fund too. Unfortunately, it went haywire in 2008. We promptly abandoned it, only to see the strategy recovered sharply in 2007.

So the big question is: how do we know whether the loss of cointegration is temporary, and how do we know when to resume trading a pair?

To answer the first question, it is often necessary to go beyond the technicals, and delve into the fundamentals of pair. Take GLD-GDX as the example. When I taught my pairs trading workshop in South Africa, several  portfolio managers in attendance told me that there are 2 reasons why gold spot price diverged from gold miners' stock prices. Firstly, due to the sharp increase in oil prices during the first half of 2008, it costs the gold miners a lot more in energy to extract the gold from the ground, hence the gold miners' income lags behind the rise in gold prices. Secondly, many gold miners hedge their exposure to fluctuating gold prices with derivatives. Hence when gold price rise beyond a certain limit, the gold miners cease to benefit from this rise. Recently, the Economist magazine published an article that essentially confirms this view. But further confirmation can be gained by introducing oil (future) price into the cointegration equation. If you do that, and if you trade this triplet of GLD-GDX-USO, you will find that it is profitable throughout the entire period from 2006-2010. If you find trading a triplet too complicated, you can at least backtest a trading filter such that you will cease to trade GLD-GDX whenever USO goes beyond (above, and maybe below too) a certain band. If you have done all these backtests, you will have a plan in place to tell you when to resume trading this pair. But even if you haven't done this backtest, and you find that you need to stop trading a pair because of cumulating losses, you should at least continue paper trading it to see when it is turning around!

(By the way, if you think trading ETF pairs offers too low returns due to the low leverage allowed, consider the single stock futures on ETF's trading on the OneChicago exchange. Certainly the future on GDX is available there, while you might just trade the futures GC and CL directly on CME. There is, of course, the usual caveat that applies to futures pairs trading: the switch from contango to backwardation and vice versa can ruin many a pairs-trading strategy, even if the spot prices remain cointegrating. But that's a story for another time.)

Thursday, June 02, 2011

Even more on news driven trading

News driven trading is even more in vogue today than when I last mentioned it, judging from the increasing number of vendors (e.g. Ravenpack, Sensobeat, Recorded Future, etc.) and researchers pitching their wares. Not only are traditional financial and economic news deemed important, but researchers have found even blog posts (at least those on Seeking Alpha) and Twitter (Hat tip: Satya and William) to be predictive of stock prices.

One key ingredient to success in this type of trading is of course the ability to gain access to breaking news ahead of other traders. On the macroeconomic news front, the MIT Billion Prices project has spun off a company called PriceStats to deliver daily consumer product price index to subscribers. PriceStats compiles this index by continuously scanning online retailers' websites, and hopefully provides a preview of the official CPI numbers. Whether this is useful for futures and currencies traders is of course subject to their rigorous backtests, though the chart displayed on their website does suggest that the daily price index is a leading indicator of the CPI.

There is an important caveat to using news trading: not all news are equal. So another key ingredient to success is to carefully differentiate between the different types of news and backtest their predictive abilities separately. For example, I recall some research has indicated that an analyst downgrade of a stock from a "hold" to a "sell" rating has more impact than from "buy" to "hold" rating.

My own experience with news driven trading is that for all this trouble, the trading opportunities are relatively few compared to pure price driven trading, the consistency of success is low, and finally the profitability lifespan is short. If you have better experience, do share it with us.

Tuesday, May 17, 2011

A platform, a shareware site, and some courses for quant traders

I mentioned in various places that Alphacet Discovery is an industrial strength integrated platform for backtesting and implementing quantitative trading strategies. But of course, it has many competitors, one of which is a relatively new company called Deltix. Deltix has the distinction of offering a full Matlab interface, which is convenient if you are already a Matlab programmer. (Full disclosure: I previously have a consulting relationship with Alphacet, but have none with Deltix.)

There is also a new website for sharing trading strategy software called Quantonomics. In the words of its founder Joshua, the goal is to "connect programmers and stock traders". Joshua also told me that he will create a custom application on his site for any of you readers as a gift!

A colleague of mine in Singapore, Dr. Li Haksun, who was previously a quant with UBS and BNP Paribas, is offering a course on quantitative trading strategy in July. It covers more theoretical concepts than my own courses: e.g. hidden markov model, stochastic control, and Kalman filters are included.

And of course, my own workshops on Backtesting and Statistical Arbitrage will be offered again in London next week.

Tuesday, May 10, 2011

Time-of-day effects in FX trading

As I mentioned in a previous post, one of the main ingredients of success in constructing a profitable momentum trading strategy in Forex (and futures) is to pay attention to the entry and exit times. I haven't seen any good momentum strategy that has "time-translation invariance", i.e. works without reference to a fixed time of the day. The fixed time can refer to a benchmark level of the market (e.g. the previous close), or it can be the entry or exit time.  (This is in contrast to mean-reverting strategies where the reference price can often be just a moving average.) A recent research paper (Hat tip: William) points to another example of such time-of-day effects in FX markets: a currency typically depreciates during its local trading hours.

Saturday, April 23, 2011

The many facets of linear regression

Many years ago, a portfolio manager asked me in a phone interview: "Do you believe that linear or nonlinear models are more powerful in building trading models?" Being a babe-in-the-woods, I did not hesitate in answering "Nonlinear!" Little did I know that this is the question that separate the men from the boys in the realm of quantitative trading. Subsequent experiences showed me that nonlinear models have mostly been unmitigated disasters in terms of trading profits. As Max Dama said in a recent excellent article on linear regression: "...when the signal to noise ratio is .05:1, ... there’s not much point in worrying about [higher order effects]". One is almost certain to overfit a nonlinear model to non-recurring noise.


Until recently, I have used linear regression mainly in finding hedge ratios between two instruments in pair trading, or more generally in finding the weightings (in number of shares) of individual stocks in a basket in some form of index arbitrage. Of course, others have found linear algebra useful in principal component analysis and more generally factor analysis as well. But thanks to a number of commenters on this blog as well as various private correspondents, I have begun to apply linear regression more directly in trading models.


One way to directly apply linear regression to trading is to use it in place of moving averages. Using moving average implicitly assumes that there is no trend in a price series, that the mean of the prices will remain the same. This of course may not be true. So using linear regression to project the current equilibrium price is sometimes more accurate than just setting it equal to a moving average. I have found that in some cases, this equilibrium price results in better mean-reverting models: e.g. short an instrument when its current price is way above the equilibrium price. Of course, one can also use linear regression in a similar way in momentum models: e.g. if the current price is way above the equilibrium price, consider this a "breakout" and buy the instrument. 


Max in his article referenced above also pointed out a more sophisticated version of linear regression, commonly called "weighted least squares regression" (WLS). WLS is to linear regression what exponential moving average (EMA) is to simple moving average (SMA): it gives more weights to recent data points. Indeed I have found that EMA often gives better results than SMA in trading. However, so far I have not found WLS to be better than simple least squares. Max also referenced an article which establishes the equivalence between weighted least squares and Kalman filter. Now Kalman filter is a linear model that is very popular among quantitative traders. The nice feature about Kalman filter is that there is very few free parameters: the model will adapt itself to the means and covariances of the input time series gradually. And furthermore, it can do so one-step at a time (or in technical jargon, using an "online" algorithm) : i.e., there is no need to separate the data into "training" and "test" sets, and no need to define a "lookback" period unlike moving averages. It makes use of "hidden states" much like Hidden Markov Models (HHM), but unlike HHM, Kalman filter is faithfully linear.


I haven't used Kalman filter much myself, but I would welcome any comments from our readers on its usage. Also, if you know of other ways to use linear regression in trading, do share with us here!



Friday, March 11, 2011

Momentum strategies in futures and forex

I have long found that it is easier to find good (i.e. high Sharpe ratio) mean-reverting strategies than good momentum strategies. Partly, that is because I was mainly a stock trader instead of a futures/currencies trader, and individual stocks mean-revert most of the time. There are exceptions, such as after special corporate events such as earnings announcements, and I have tested momentum strategies based on these events. But the success of even these event-driven strategies has been uneven, especially since more traders become aware of them.

Now that I am focusing more on trading futures and currencies, I have gradually been introduced to the world of momentum investing. There is a good book in this area that deserves to be better known: Joe Duffy's The Ultimate Trading Robot, which is an almost step-by-step guide to constructing futures trending strategies that rely on prices alone. Another example would be the London Breakout strategy mentioned by our reader Bernd in the comments here. After studying these examples, I realized why my previous, rather desultory, search for momentum strategies in the futures and FX markets had been in vain: the overnight gap in these markets seems critical. For futures, the overnight gap is obvious, but in the case of the London Breakout strategy, for example, the trader has the task defining for herself what the optimal closing and opening times are in order to compute the gap. Intraday trend without an overnight breakout does not seem persistent enough to be traded profitably. I also wonder if there is a more elegant (i.e. mathematical) way to quantify such breakout phenomena without using the traditional technical indicators.

If you know of ideas for good momentum strategies, you are most welcome to share and discuss them here!

Tuesday, January 25, 2011

High frequency trading ideas

I just started reading Larry Harris' book "Trading and Exchanges" (thanks to Max Dama's glowing book review) and already a couple of potential high frequency trading techniques stood out:

"Quote matching" - a technique whereby front-runners place a limit buy order just a cent (for stocks) higher than the best bid price. If the order is filled, they then place a limit sell order just a cent lower than the best ask. Assuming the best bid-ask quotes don't move, the worst they can do is to lose 1 cent by selling the share back to the best bidder, while the most profit they can make is the bid-ask spread plus rebates for providing liquidity minus 2 cents by having the sell long limit order filled. This could work out quite profitably if the bid-ask spread is wide. But of course, the best bid-ask do change constantly, so front-runners would need to cancel and correct their limit orders constantly, and the optimal algorithm for doing this could get quite complicated. Meanwhile, if you are a bona fide liquidity provider, you would have to avoid providing this free option to the front-runners by constantly monitoring who is in front of you. As usual, this chess game can quickly degenerate into an HFT arms race.

"Manipulation of stop orders" - a.k.a. "gunning the market", a technique whereby the market gunners buy aggressively so as to trigger large buy stop orders that they believe are in place at a higher price. When these buy stop orders are filled, the prices are driven higher still, and these manipulators then sell their position profitably.

One of my old momentum strategies was a victim of these market gunners, and after that sad experience I refused to use stop orders any more, at least for stocks. However, here is a question for our knowledgeable readers: can other traders actually see what stop orders there are on an order book (whether for stocks, futures, or Forex markets)? And if so, would a trading robot that simulates stop orders by sending out buy market orders when the stop price is touched work better than manually placing a buy stop order on the order book?

Wednesday, January 05, 2011

Shorting the VIX calendar spread

Lately there were a few interesting discussions in the blogosphere on the profitability of shorting the VXX-VXZ spread. (See Quantum Blog and The Speculator's Ball.) For background, VXX is an ETN that tracks the first and second month of the VIX future, which in turn tracks the VIX volatility index, which in turn tracks the volatility of SPX. VXZ is the ETN that tracks the 4th - 7th months of the VIX future. During the period 2009-2010, there were 2 different reasons why shorting this "calendar spread" was profitable:

1) The VIX futures were/are in contango: i.e. the back months' futures are more expensive than the front months'.
2) The volatility of SPX was decreasing with time.

However, some traders seem to think that either one of these conditions is enough to ensure the profitability of shorting a calendar spread.  It is not. (Otherwise, life as a futures trader would be too easy!)

To see this, let's resort to a simplistic linear approximation to a model of futures prices. From John Hull's book on derivatives, section 3.12, the price of  a future which matures at time T is

F(t, T)=E(ST)exp(c(T-t)),

where E(ST) is the expected value of the spot price at maturity, c is a constant, and t is the current time. If the futures are in contango, then c > 0.

If we assume that abs(c) is small, and T-t is also small (i.e. not too far from maturity), and that the expected value of the spot price changes slowly, we can linearize this formula as

F=(a+b(T-t))*(1+c(T-t))

If the market expects the future spot price to increase, then b > 0.

After a few simple algebraic steps, you can verify that the calendar spread's price is proportional to

F(t, T1)-F(t, T2) ~ bct

where T1 < T2 (i.e. F(t, T1) is the front month's price, and F(t, T2) the back month's).

This is a satisfyingly illustrative result. It says that shorting this calendar spread will be profitable if

A) futures are in contango and the expected spot price in the future is decreasing; or else
B) futures are in backwardation and the expected spot price in the future is increasing.

So what is the situation today? Will it still be profitable to short this spread? As our fellow bloggers have pointed out, VIX futures are still in contango, but the market is expecting volatility to increase in the future over the last month or so. So this may no longer be a profitable trade anymore.

Thursday, November 18, 2010

Columbia Workshop on Financial Engineering

Our readers in New York may be interested in this finance workshop at Columbia University tomorrow.
I am particularly interested in the talk by Kent Daniel on "Characterizing Momentum", and by Doug Borden (of Knight Equity Markets) on "Stochastic Control Theory in High-Frequency Trading". Doug's talk can be downloaded here.


Sunday, October 10, 2010

Data mining and artificial intelligence update

Long time readers of this blog know that I haven't found data mining or artificial intelligence techniques to be very useful for my own trading, for they typically overfit to non-recurring past patterns. (Not surprisingly, they are much more useful for driverless cars.) Nevertheless, one must keep an open mind and continues to keep tabs on new developments in this field.

To this end, here is a new paper written by an engineering student at UC Berkeley which uses "support
vector machine" together with 10 simple technical indicators to predict the SPX index, purportedly with 60% accuracy. If one includes an additional indicator which measures the number of news articles on a stock in the previous day, then the accuracy supposedly goes up to 70%.

I did not have the chance to reproduce and verify this result yet, but I invite you to try it out and share your findings here. If you do so, you may find this new data mining product called 11Ants Analytics useful. It is an Excel-based software that includes 11 machine learning algorithms including the aforementioned support vector machines. It also includes decision trees which are sometimes quite useful in automatically generating a small set of trading rules from an input set of technical indicators. (Whether those rules remain profitable in the future is another question!) If you have tried this product, I would also appreciate your comments here.

(If you are a die-hard MATLAB fan, support vector machines are available in their Bioinformatics Toolbox, and classification and decision trees in their Statistics Toolbox.)

Saturday, October 02, 2010

The main virtue of buying options

I realized that I have omitted the most obvious virtue of trading options instead of stocks in my last post: the much more attractive reward-risk ratio for options.

Suppose your stock strategy generated a buy signal. You can either buy the stock now, or you can buy an ATM call. If you buy the stock, you are of course benefiting from 100% of the upside potential of the stock price movement, but you are similarly exposed to 100% of the downside risk. Indeed you can lose the entire market value of the stock. If you buy the call, you will benefit from > 50% of the upside potential of the stock price, assuming that your holding period is so short that the time value will not dissipate much. As the stock price rises, so does your delta. (It increases from 0.5 to 1.) But what about the downside risk? All you can lose is the option premium, usually << 50% of the market value of the stock.

In other words, while one may be tempted to hedge a large stock position with stock index futures, there is no need to hedge an equivalent call option position. This should simplify your strategy implementation and reduce risk management costs (i.e. the probable loss on your short futures position).

Given that I am a short-term trader anyway, I can't figure out why I have been trading stocks instead of options all these years! (Aside from the caveats detailed in the previous post.)

Saturday, September 25, 2010

Implementing stock strategies using options

There are many stock trading strategies that are quite attractive in terms of Sharpe ratios, but not very attractive in terms of returns. (Pairs trading comes to mind. But in general, any market neutral strategy suffers from this problem.)  Certainly, one cannot feed a family with annualized returns in the single or low double digits, unless one already has millions of dollars of capital. One way to solve this dilemma is of course to join a proprietary trading group, where we would have access to perhaps x30 leverage. Another way is to implement a stock trading strategy using options instead, though there are a sizable number of issues to consider. (I recently brushed up on my options know-how by reading the popular "Options as a Strategic Investment".)
  1. Using options will allow you to increase your leverage beyond the Reg T x2 leverage (or even the day trading x4 leverage) only if you buy options only, but not selling them. For example, to implement a pairs trading strategy on 2 different stocks, you would have to buy call options on the long side, and buy put options on the short side (but not sell call options). Otherwise the margin requirement for selling calls is as onerous as shorting the underlying stock itself.
  2. The effective leverage is computed by multiplying the delta of the option by the underlying stock price divided by the option premium. If you buy an out-of-money (OTM) option, the delta will be small (smaller than 0.5), but the option premium is small also. Vice versa for an in-the-money (ITM) option. So you would have to find the optimal strike price so that the effective leverage is maximized. I personally choose to buy an at-the-money (ATM) call or slightly ITM call without actually computing the optimized strike, but perhaps you have reached a different conclusion?
  3. Naturally, the shorter the time-to-expiration, the cheaper the option and higher the effective leverage. Additionally, for ITM options, their deltas increase as we get closer to expiration, which also contributes to higher effective leverage. However, the time-to-expiration must of course be longer than the expected holding period of your position, otherwise you would incur the transaction cost of rolling over to the further-month options.
  4. The discussion of finding the right strike price based on its delta is moot if your brokerage's API does not provide you with delta for your automated trading system. In theory, Interactive Brokers's API provide deltas for whole options chains, and quant2ib's MATLAB API will pass these on to your MATLAB exeuction program too. However, I have not been successful in retrieving deltas using quant2ib's API. If you have encountered a similar problem, and perhaps have found the reason/cure for this, please let me know. For now, I am reduced to assuming that all my near ATM calls for different stocks have the same delta, and I increase this common value from 0.5 to close to 1 as time passes.
  5. Options don't have MOO, LOO, MOC or LOC order types. If one uses market orders to buy at the open or close, one would incur significant transaction costs due to the much wider bid-ask spread compared to stocks. I try to use limit orders on options orders as much as possible.
If you have used options to implement stock trading strategies, and have experiences with these or other issues, please do share them here.

====

Reminder: my next pairs trading workshop will take place in New York on October 26-27th.

Sunday, August 22, 2010

Phantom quotes

Have you ever got the feeling that your market orders are often filled at prices worse than the NBBO displayed on your trading screen? Apparently, this may be the result of deliberate manipulation of the market by high frequency traders. These HF traders submit thousands of quotes per second to the NYSE ("quote stuffing") and then cancel them within 50 ms. This slows down the exchange data queue so much that by the time a quote is transmitted to you, it is stale already, even if your trading server is collocated at the exchange. (Checking the time stamp of the quote is of no help: the time stamp is based on the time the quote enters the queue, not when it exits the queue.)

If you can no longer believe in the quotes, is there any integrity left in the market? Much as I think that HFT may be useful liquidity providers, I can't see how this specific practice could be good for anyone over the long term.

(Hat tip: Jim Liew of Alpha Quant Club.)

Saturday, August 14, 2010

What are we to do with Sharpe ratio?

I wrote several times before how useless Sharpe ratio is for certain types of strategies: see here and here. Not only is a high Sharpe ratio quite useless in telling you what damage extreme events can do to your equity, a low Sharpe ratio is also quite useless in telling you what spectacular gain your strategy might enjoy in the event of a catastrophe. I came across another brilliant example of the latter category in the best-selling book "The Big Short", where the author tells of the story of the fund manager Mike Burry.

Mike Burry started buying credit default swaps in 2005, essentially an insurance policy on mortgage-backed securities, betting that there will be widespread defaults on mortgages. Of course, we now know how this story would turn out: Mike Burry made $750 million in 2007 alone.  But there was nothing but pain for the fund manager and his investors in 2005-2006, since they had to pay an annual premium of 8% of the portfolio.  Investors who measured the performance of this strategy using Sharpe ratio, without knowing the details of the strategy itself, would be quite justified to think that it was an utter disaster prior to 2007. And indeed, many of them lost no time in trying to pull out their investments.

So what are we to do with Sharpe ratio, with its inherent reliance on Gaussian distributions? Clearly, it is useful for measuring high frequency strategies which you can count on to generate consistent returns every day, but which has limited catastrophic risks. But it is less useful for measuring statistical arbitrage strategies that hold positions over multiple days, since there may well be substantial hidden catastrophic risks in these strategies that would not be revealed by their track record and standard deviation of returns alone. As for strategies that are designed to benefit from catastrophes, such as Mike Burry's CDS purchases or Nassim Taleb's options purchases, it is completely useless. If I were to allocate my assets over different hedge funds, I would be sure to include some funds in the first category to generate cash flows for my daily needs, as well as funds in the last category to benefit from the infrequent black-swan events. As for the funds in the middle category, I am increasingly losing my enthusiasm.

Friday, July 30, 2010

Pair trading technologies update

Pair trading was invented two decades ago, but automating its implementation has only recently become fashionable with independent traders. But once the spotlight is on, innovations come fast and furious. Here are a number of recent developments that I find interesting:


1. I mentioned previously the software called quant2ib. It is an API which allows us to get market data and send orders from a Matlab program to Interactive Brokers (IB). I have used it extensively for our trading, and it is as reliable as IB's native API. Their latest version now includes functions for constructing a "combo" security. This combo security can be pairs of stocks, ETF's, futures, etc. (with the notable exception of currencies), and the API allows you to get market data as well as to submit orders on a combo. This is a huge improvement because you can now automatically trade a pair of securities as one unit by submitting limit orders on the combo. (Previously, you would have had to submit market order on at least one side of the pair, and this would have required your program to continuously monitor the market prices and send orders when appropriate. Or else you had to give up using the API and manually enter a "generic combo" limit order in IB's TWS.)

2. Alphacet Discovery also has the ability to send limit orders on pairs, due to its partnership with Knight Trading. Besides, based on a demo that I have recently seen, they also now have great pairs portfolio and execution reporting functionality. (Full disclosure: I used to consult for them.)

3. IB itself has released a "Scale Trader" algorithm that can be applied to combos (see 1. above. Hat tip: Mohamed.) I can't explain this better than their press release: "... ScaleTrader algorithm allows clients to create conditions under which a long position in one stock is built while simultaneously creating an offsetting short position in the other. The ScaleTrader is named because investors can 'scale-in' to market weakness by setting orders to buy as the market moves lower. Similarly, sell orders can be 'scaled' into when a market is rising. The ScaleTrader algorithm can be programmed to buy the spread and subsequently take profit by selling the spread if the difference reaches predetermined levels set by the user." In other words, it allows us to automatically implement the "parameterless trading" or the "averaging-in" strategy that I blogged about previously without any programming on our part!

Speaking of pair trading, I will be teaching my first New York workshop in October.  (My editor inevitably picks touristy locations for these workshops. My London workshop takes place across the street from the Tower of London, my New York workshop is across from the new World Trade Center, and my Hong Kong workshop is in the "Golden Mile" shopping district of Tsim Sha Tsui.)

Saturday, May 29, 2010

The Quants

Once in a while, a book about trading written for the general public contains some useful nuggets even for professionals.  Fortune's Formula was one. It introduced me to the world of Kelly's formula, Universal Portfolios, and the maximization of compounded growth rate. The Quants, by WSJ reporter Scott Patterson, is another. (Hat tip to my partner Steve for telling me about it.)

What is the most important take-away in The Quants? No, it is not that you should learn to become a master poker player or chess player before hoping to make it big, though you would think that given Patterson's exhaustive coverage of poker games played by the top quants. Among my own professional acquaintances, trader-poker-players are still a minority.

The most important take-away is what ex-employees said about Renaissance Technologies: "there is no secret formula for the fund's success, no magic code discovered decades ago by geniuses .... Rather, Madallion [Fund]'s team of ninety or so Ph.D.'s are constantly working to improve the fund's systems, ..."

In other words, though you may not have 90 Ph.D.'s  at your disposal, you can still work on continuously improving/refining your strategies, improving the engineering of your trading environment, and increasing the diversity of your strategies. And though you may still not archive 60-70% annualized returns every year, you will nevertheless enjoy stable returns year after year.

By the way, it is good to see my ex-colleagues Lalit Bahl, Vincent and Stephen Della Pietra mentioned in the book, all of whom left IBM to join Renaissance many years ago, and who are extraordinarily nice and friendly guys, quite in contrast to the norm on Wall Street.

Saturday, May 22, 2010

A HFT primer

As a follow-up of my previous discussions on high frequency trading, I have invited guest blogger Jennifer Groton to share with us a quick survey of various common HFT strategies used by equities and FX traders.

==

High frequency trading strategies are under fire.  The recent trading spike in our national exchanges was duly noted as a short-circuit waiting to happen and drew immediate industry criticism of auto-trading robots. Before a witch-hunt ensues, perhaps a review of the common HFT strategies in stocks and Forex is in order. 

High-frequency firms employ a wide variety of  low-margin trading strategies that are implemented by professional market intermediaries who have invested heavily in technology. These firms claim that they make markets more efficient by enhancing liquidity and transparent price discovery to the benefit of investors.  The Forex market’s unique combination of high liquidity and low volatility make it an ideal environment for deploying HFT strategies, although many of the ideas and technology are from the equity markets.  The basic strategies fall into three categories: market-making, trending or predictive, and classic arbitrage.

Market-making strategies tend to focus on a single stock or currency pair.  Many firms in this area have been described as engaging in "rebate-capture trading", a reference to the credits that firms get for providing liquidity on most market centers.

The second group consists of mean-reversion and trending strategies. These utilize technical indicators for stocks or forex indicators for currencies, and seek to generate more return from individual trades.

The last group may involve a cross-section of trades from multiple markets.  The classic arbitrage strategy is a form of the “carry trade” that uses the prices of a domestic bond, a bond denominated in a foreign currency, the spot price of the currency, and the price of a forward contract on the currency.  If the market prices are sufficiently different from those implied in the model to cover transactions costs, then four transactions can be made to guarantee a risk-free profit.

High frequency trading is attributed with generating over 70% of the volume of trades on our equity markets.  Similar statistics are not available for forex markets, but speculating disguised as commercially necessary trades have been reported to be over two-thirds of the volume.  Liquidity and pricing transparency are the benefits offered by its advocates, but regulators and other market participants who disagree with this positive assessment are presently discounting these benefits.  Transaction taxes and time limits on orders have been proposed to mitigate the perceived risk created by HFT firms, but the wheels of Washington move slowly, even in crisis.  For the time being, there is no indication that their participation will be discontinued.   

Saturday, May 08, 2010

Are flash orders to be blamed for Dow's 1,000 points drop?

Before the smoke is clear, fingers are already pointing at flash orders. See these two NYT pieces here and here. Our reader Madan has convinced me previously that flash orders can indeed be used to  front-run other traders, but until more evidence comes in, I am yet to be convinced that they are the main culprit. Couldn't old-fashioned automated momentum programs accomplished the same thing after an initial erroneous transaction price and/or quote was reported? Perhaps you know of discussions elsewhere on the blogosphere that bring more light to the issue?

Sunday, May 02, 2010

An additional ETF pair

Many of you know that there are a number of dependable commodity-related ETF pairs that remain cointegrated ever since I mentioned them in 2006: IGE-EWC, IGE-EEM, IGE-EWA, EWA-EWC, etc. (Their latest zScores are available here to my book's readers and to Premium Content subscribers.) A recent visit to a client in South Africa prompted me to add a new one: EWA-EZA.

It is worth noting that for those country ETF pairs that cointegrate, their underlying currency cross-rates are often stationary as well. Now, there are several advantages in trading currency cross rates instead of ETF pairs. When trading a stationary cross rate, you can enter a limit order to enter and exit, but trading pairs of ETF's involve market orders on at least one side. Also, ETF's can sometimes be hard-to-borrow, and their margin requirements are much more onerous than that of currencies. However, the one major disadvantage in trading cross rates is that they are not always available on your brokerage. For example, based on the cointegration of EWA and EZA you would think that trading AUDZAR would be quite profitable. And you would be right, theoretically, except that AUDZAR is not available for trading on Interactive Brokers. If you know of a good Forex brokerage that have many emerging markets cross-rates for trading, especially those of Latin American countries, please let the rest of us know!

Saturday, April 17, 2010

How do you limit drawdown using Kelly formula?

As many of you know, I am a fan of Kelly formula because it allows us to maximize long-term growth of equity while minimizing the probability of ruin. However, what Kelly formula wont' prevent is a deep drawdown, though we are assured that the drawdown won't be as much as 100%! This is unsatisfactory to many traders and especially fund managers, since a deep drawdown is psychologically painful and may cause you to panic and shut down a strategy prematurely.

There is an easy way, though, that you can use Kelly formula to limit your drawdown to be much less than 100%. Suppose the optimal Kelly leverage of your strategy is determined to be K. And suppose you only allow a maximum drawdown (measured from the high watermark, as usual) to be D%. Then you can simply set aside D% of your initial total account equity for trading, and apply a leverage of K to this sub-account to determine your portfolio market value. The other 1-D% of the account will be sitting in cash. You can then be assured that you won't lose all of the equity of this sub-account, or equivalently, you won't suffer a drawdown of more than D% in your total account. If your trading strategy is profitable and the total account equity reaches a new high watermark, then you can reset your sub-account equity so that it is again D% of the total equity, moving some cash back to the "cash" account. Otherwise, you continue to keep the equity in the cash account separate from the equity of the trading sub-account.

Notice that because of this separation of accounts, this scheme is not equivalent to just using a leverage of L=K*D% on your total account equity. Indeed, some of you may be too nervous to use the full K as leverage, and prefer to use a leverage L smaller than K. (In fact, the common wisdom is that, due to estimation errors, it is never advisable to set L to be more than K/2, i.e. half-Kelly.) The problem with using a L that is too small is that, besides not achieving maximum growth, the portfolio market value will be unresponsive to gains or losses and will remain relatively constant. Using the scheme I suggested above will cure this problem as well, because you can apply a higher leverage L_sub to the sub-account (e.g. use L_sub = L/D%) as long as L_sub < K, so that the portfolio market value is much more sensitive to your P&L while still ensuring the drawdown will not exceed D%.

Has anyone tried this scheme in their actual trading? If so, I would be interested in hearing your experience and see if practice is as good as theory.

Saturday, February 27, 2010

Conference on the sociology of quantitative finance

A new conference called Psi-Q will be held in London this June, featuring luminaries in the academic quantitative finance world, as well as risk and fund managers from various banks and hedge funds. Example topics:
  • How did shared beliefs, practices, ways of calculating, and technical systems impact evaluation of asset-backed securities and CDOs before and during the credit crises?
  • Was that Lucky or Good? Creating a framework for skill attribution in finance, business management and other risky endeavors.
  • The “backing out” phenomena observed in options markets:  how traders use models to imply independent variables consistent with market observed pricing, and where enough traders can be wrong about the expected results and the backed-out positions can send the wrong message.
Sounds like an interesting bird's eye view of quantitative finance.

Thursday, February 18, 2010

Pairs Trading Workshop in Hong Kong

For my readers in Asia, I will be conducting a pairs trading workshop in Hong Kong on March 10-11. This workshop is organized by the Technical Analyst magazine and is similar to the one I gave in London last year.
However, I have added a few useful insights based on audience feedback. As always, no prior knowledge of Matlab or advanced statistics is assumed. The numerous in-class exercises should be sufficient to bring your Matlab programming skills up to speed.

Sunday, January 31, 2010

A method for optimizing parameters

Most trading systems have a number of parameters embedded, parameters such as the lookback period, the entry and exit thresholds, and so on. Readers of my blog (for e.g., here and here) and my book would know my opinion on parameter optimization: I am no big fan of it. This is because I believe financial time series is too non-stationary to allow one to say what was optimal in the backtest is necessarily optimal in the future. Most traders I know would rather trade a strategy that is insensitive to small changes in parameters, or alternatively, a "parameterless" strategy that is effectively an average of models with different parameters.

That being said, if you can only trade one model with one specific set of parameters, it is rational to ask how one can pick the best (optimal) set of parameters. Many trading models have a good number of parameters, and it is quite onerous to find the optimal values of all these parameters simultaneously. Recently, Ron Schoenberg published an article in the Futures Magazine that details a way to accomplish this with just a tiny amount of computer power.

The key technique that Ron uses is cubic polynomial fit of the P&L surface as a function of the parameters. Ron uses the VIX RSI strategy in Larry Connors' book "Short Term Trading Strategies That Work" as an example. This strategy has 5 parameters to be optimized, but Ron only needs to compute the P&L for 62 different sets of parameters, and the whole procedure only takes 58 seconds.

Although Ron has confirmed that most of the parameters that Connors picked are close to optimal, he did find a few surprises: namely, that RSI of period 3 or 4 is significantly more profitable than the 2 that Connors used, at least in the backtest period.

Now, for a true test of this optimization, it would be helpful if Ron performed this optimization withholding some out-of-sample data, and see if these parameters are still optimal in that withheld data set. Since he didn't do that, we need to wait for another year to find out ourselves!

Tuesday, January 19, 2010

Excel ADF test

Some readers have asked whether there is an Excel version of the ADF test for cointegration (mentioned in articles here or here.) You can download one such package here (Hat tip: Bruce H.).

And as always, you can download the Matlab version from spatial-econometrics.com.

Saturday, January 09, 2010

Does Averaging-In Work?

Ron Schoenberg and Al Corwin recently did some interesting research on the trading technique of "averaging-in". For e.g.:  Let's say you have $4 to invest. If a future's price recently drops to $2, though you expect it to eventually revert to $3. Should you

A) buy 1 contract at $2, and wait for the price to possibly drop to $1 and then buy 2 more contracts (i.e. averaging-in); or
B) buy 2 contracts at $2 each;  or
C) wait to possibly buy 4 contracts at $1 each?

Let's assume that the probability of the price dropping to $1 once you have reached $2 is p. It is easy to see that the average profits of the 3 options are the following:
A) p*(1*$1+2*$2) + (1-p)*(1*$1)=1+4p;
B) 2; and
C) p4*$2=8p.

Profit A is lower than C when p > 1/4, and profit A is lower than profit C when p > 1/4. Hence, whatever p is,  either option B or C is more profitable than averaging in, and thus averaging-in can never be optimal.

From a backtest point of view, the Schoenberg-Corwin argument is impeccable, since we know what p is for the historical period. You might argue, however, that financial markets is not quite stationary, and in my example, if the historical value of p was less than 1/4, it is quite possible that the future value can be more than 1/4. This is why I never make too much effort to optimize parameters in general, and I can sympathize with traders who insist on averaging-in even in the face of this solid piece of research!

Thursday, December 24, 2009

Selecting tradeable pairs: which measure to use?

A guest blog by Paul Farrington

One of the most important factors in statistical arbitrage pairs trading is the selection of the paired instruments.  We can use basic heuristics to guide us, such as grouping stocks by industry in the anticipation that stocks with similar fundamental characteristics will share factor risk and tend to exhibit co-movement.  But this still leaves us with potentially thousands of combinations.  There are some statistical techniques we can use to quantify the tradeability of a pair: one approach is to calculate the correlation coefficient of each pair's return series. Another is to consider cointegration measures on the ratio of the prices, to see if it remains stationary over time.

In this article I briefly summarise the alternative approaches and apply them to a universe of stock pairs in the oil and gas industry.  To measure how effective each measure is in real world trading, I back test the pairs using a simple means reversion system, then regress the generated win rate against the statistical results.  Some basic insights emerge as to the effectiveness of correlation and cointegration as tools for selecting candidate pairs.

Please visit http://www.paulfarrington.com/research/Selecting%20tradeable%20pairs.htm for details of my methodology and results.

Friday, December 18, 2009

Public service announcements for quants

   1.  Conference on 'Computational Topics in Finance', February 19/20, 2010, National University of Singapore. The topics will include using R/Rmetrics in finance, but the conference is by no means confined to R. See http://www.rmetrics.org/.

   2.  Consulting position (6-month renewable contract) available at a major Canadian bank in Toronto:  research in  various mathematical algorithms used for pricing of interest rate derivative instruments like swaps, caps, swaptions, FRAs. Please contact their recruiter at http://www.linkedin.com/pub/kevin-p-w-wang/6/899/29a.

   3.  A free copy of Chapter 8 of "High Probability ETF Trading" which I mentioned here is now available for download.

Sunday, December 06, 2009

Are financial speculations really "harmful human activities"?

It is worrisome when not one but two eminent economists denounced financial speculation as "harmful human activities" in the short space of 2 weeks. (See Paul Krugman's column here and Robert Frank's here.) It is more worrisome when their proposed cure to this evil is to apply a financial transaction tax to all financial transactions.

Granted, you can always find this or that situation when financial speculation did cause harm. Maybe speculation did cause the housing bubble. Maybe speculation did cause an energy price bubble. In the same vein, you can also argue that driving is a harmful human activity because cars did cause a few horrific traffic accidents.

No, we can't focus on a few catastrophes if we were to argue that financial speculation is harmful. We have to focus on whether it is harmful on average. And on this point, I haven't seen our eminent economists present any scientific evidence. On the other hand, as an ex-physicist and an Einstein-devotee, I can imagine some  thought experiments (or gedankenexperiment as Einstein would call them), where I can illustrate how the absence of financial speculation can clearly be detrimental to the interests of the much-beloved long-term investors. To make a point, a gedankenexperiment is usually constructed so that the conditions are extreme and unrealistic. So here I will assume that the financial transaction tax is so onerous that no hedge funds and other short-term traders exist anymore.

Gedankenexperiment A: Ms. Smith just received a bonus from her job and would like to buy one of her favorite stocks in her retirement account. Unfortunately, on the day she placed her order, a major mutual fund was rebalancing its portfolio and had also decided to shift assets into that stock. In the absence of hedge funds and other speculators selling or even shorting this stock, the price of that stock went up 40% from the day before. Not knowing that the cause of this spike was a temporary liquidity squeeze, and afraid that she would have to pay even more in the future, Ms. Smith paid the ask price and bought the stock that day. A week later, the stock price fell 45% from the peak after the mutual fund buying subsided. Ms. Smith was mortified.

Gedankenexperiment B: Mr. Smith decided that the stock market is much too volatile (due to the lack of speculators!) and opted to invest his savings into mutual funds instead. He took a look at his favorite mutual fund's performance, and unfortunately, its recent performance seemed to be quite a few notches below its historical average. The fund manager explained on her website that since her fund derived its superior performance from rapidly liquidating holdings in companies that announced poor earnings, the absence of liquidity in the stock market often forced her to sell into an abyss. Disgusted, Mr. Smith opted to keep his savings in his savings account.

Of course, our economists will say that the tax is not so onerous that it will deprive the market of all speculators (only the bad ones!?). But has anyone studied if we impose 1 unit of tax, how many units of liquidity in the marketplace will be drained, and in turn, how many additional units of transaction costs (which include implicit costs due to the increased volatility of securities) would be borne by an average investor, who may not have the luxury of submitting a limit order and waiting for the order to be filled?

Friday, November 27, 2009

Picking up nickels in front of steamrollers

When I was growing up in the trading world, high Sharpe ratio was the holy grail. People kept forgetting the possibility of "black swan" events, only recently popularized by Nassim Taleb, which can wipe out years of steady gains in one disastrous stroke. (For a fascinating interview of Taleb by the famous Malcolm Gladwell, see this old New Yorker article. It includes a contrast with Victor Niederhoffer's trading style, plus a rare close-up view of the painful daily operations of Taleb's hedge fund.)

Now, however, the pendulum seems to have swung a little too far in the other direction. Whenever I mention a high Sharpe-ratio strategy to some experienced investor, I am often confronted with dark musings of "picking up nickels in front of steamrollers", as if all high Sharpe-ratio strategies consist of shorting out-of-the-money call options.

But many high Sharpe-ratio strategies are not akin to shorting out-of-the-money calls. My favorite example is that of short-term mean-reverting strategies. These strategies not only provide consistent small gains under normal market conditions, but in contrast to shorting calls, they make out-size gains especially when disasters struck. Indeed, they give us the best of both worlds. (Proof? Just backtest any short-term mean-reverting strategies over 2008 data.) How can that be?

There are multiple reasons why short-term mean-reverting strategies have such delightful properties:
  1. Typically, we enter into positions only after the disaster has struck, not before.
  2. If you believe a certain market is mean-reverting, and your strategy buy low and sell high, then of course you will make much more money when the market is abnormally depressed.
  3. Even in the rare occasion when the market does not mean-revert after a disaster, the market is unlikely to go down much further during the short time period when we are holding the position.
"Short-term" is indeed the key to the success of these strategies. In contrast to the LTCM debacle, where they would keep piling on to a losing position day after day hoping it would mean-revert some day, short-term traders liquidate their positions at the end of a fixed time period, whether they win or lose. This greatly limits the possibility of ruin and leaves our equity intact to fight another day in the statistical game.

So, call me old-fashioned, but I still love high Sharpe-ratio strategies.

Wednesday, November 04, 2009

In praise of ETF's

I have learned some years ago that ETF's are strange and wonderful creatures. Simple, long-only mean-reverting strategies that work very well on ETF's, won't work on their component stocks. (Check out a nice collection of these strategies in Larry Connors' book "High Probability ETF Trading". He has also packaged these strategies into a single indicator, the ETF Power Ratings, on tradingmarkets.com.) Simple pair trading strategies like the one I discussed in my book, also work much more poorly on stocks than on ETF's. Why is that?

Well, one obvious reason is that, as Larry mentioned in his book, ETF's are not likely to go bankrupt (with the notable exception of the triple-leveraged ETF's, as I explained previously), because a whole sector or country is not likely to go bankrupt. So you can pretty much count on mean-reversion if you are on the long side.

Another obvious reason is that though there are news which will affect the valuation of a whole sector or country, these aren't as frequent or as devastating as news affecting individual stocks. And believe me, news is the biggest enemy of mean-reversion.

But finally, I believe that the capital weightings of the component stocks also play a part in promoting mean-reversion. Typically, weighting of a component stock increases with its market capitalization, though not necessarily linearly. Perhaps large-cap stocks are more prone to mean-reversion than small-cap stocks? But more intriguingly, can we not construct a basket of stocks, with custom-designed weightings, with the objective of optimizing its short-term mean-reversion property? I (and others before me) have done something similar in constructing a basket of stocks that cointegrate best with an index. Can we not construct a basket that is simply stationary (with perhaps a constant drift)?

Now, perhaps you will agree with me that ETF's are strange and wonderful creatures.

Sunday, October 11, 2009

The best environment for quantitative trading

Let me talk about a topic that is far more mundane than the usual high-brow theoretical discussions of strategies and algorithms, but that has no less long-term impact on the bottom line: what is the best office environment for research and execution of quantitative trading strategies?

I have worked in different office environments before, so I feel qualified to offer an informed opinion.

At Morgan Stanley, I huddled over a desk that is semi-partitioned from the rest of the office: nobody could see or bother me unless I or they stood up. At Credit Suisse, I shared an office with 2 other prop trading colleagues, one of whom was prone to freely sharing his opinion on various current affairs with his officemates. (On the other hand, he complained my biting an apple for lunch was too loud for him.) At Maple, a hedge fund in New Jersey, I shared an office with about 100 other colleagues on the trading floor, many of whom were prone to same opinion-sharing temptation.

Here at my own firm, I sit in solitude (except for my cat) in my basement office, my beloved classical FM streaming over the internet, my desktop electronically connected to my partner in our Chicago office, our trading servers at Amazon and elsewhere, and other clients and partners around the world, but unmolested throughout the day unless I voluntarily pick up the phone or answer an email or instant message.

Can you guess which environment is the one I find the most productive? Which one has the least stress? And which one contributes most to the bottom line of my employers/partners/clients?

(Hint 1: read Timothy Ferriss' book The 4-Hour Workweek. This guy checks his email only once a week.)

(Hint 2: my trading Sharpe ratio went from negative to >7.)

P.S. I look forward to meeting some of you at the Automated Trading Conference in London this Friday (my talk will start at 0900), and others at my pairs trading workshop on the preceding two days.

Sunday, September 20, 2009

Are flash orders really so bad?

I confess I don't know much about flash orders, not being one of the Big Boys on the Street, until I read that the SEC is banning them. (For a clear diagrammatic explanation of flash orders, see here. For a refutation of some of the myths and misunderstanding surrounding flash orders, see here.)

It seems to me that flash orders can be understood as "request for liquidity" issued to various potential market makers/liquidity providers, not unlike the usual "request for quotes" (RFQ) common in other industries. They are issued when there is not enough liquidity on a specific exchange to satisfy an investor's need, and they ultimately benefit investors by lowering their transaction costs. The fact that high frequency traders are able to make lots of money by providing this liquidity is besides the point. Liquidity providers are supposed to make money by providing liquidity!

Some people, including Senator Charles Schumer and this New York Times op-ed, believe that flash orders are akin to front-running, a clearly illegal trading activity. But they are wrong. Front-running means that if you know someone is going buy a stock, you step in front of them
and buy it cheaply first, hoping to sell it to this slower buyer at a higher price. In the case of flash orders, the high frequency traders are instead selling this stock to the original investor, often at a lower price than available elsewhere and thus benefiting this investor, hoping that the prices will come down in the future after this liquidity need subsides. This is manifestly not illegal. This is what a market is built for!

Another way to understand that flash orders are not at all front running is that anybody, including you and me, are free to put in limit orders at the same price as those of the high frequency traders, way ahead of time, in a specific exchange, and become liquidity providers ourselves. You don't have to wait for a "request for liquidity" before doing so. And presumably you will reap the same benefits as the high frequency traders. You are not taking any additional risks over the HF traders either, since if no requests for liquidity ultimately arrive, you are not any worse off for wear. You cannot begrudge the profits of the HF traders just because you didn't put the limit orders in place beforehand!

Maybe there are some other angles which I miss which can convince me that flash orders are evil. But until my kind readers convince me otherwise in the comments section, I will regard this piece of legislation as another SEC attempt at demagoguery.

Friday, September 11, 2009

Can a trader be a do-gooder?

It occurs to me that the only way in which a trader can become more than a completely selfish, self-enriching, narcissistic person is to trade well enough so that you can manage other people's money and thus saving these investors from crooks and charlatans (provided you are convinced you are not a crook and charlatan yourself).

Other traders have advanced other arguments in favor of trading. But I am not convinced by them.

They say that we provide liquidity to other long-term investors who may need to liquidate their investments. But then, this applies only to mean-reversal strategies. Momentum strategies take away liquidity from the market, and in some cases exacerbating price bubbles. Certainly not something your grandma would approve.

Others argue that momentum strategies help disseminate information about companies through quick price movements. But can't we just watch Bloomberg or CNBC? Do we really need some devious insiders to convey that information to the rest of us through price movements?

No, I think that independent trading should serve only one purpose (besides short-term self-sustenance): as training and preparation to become a fund manager. Once you graduated from independent trading, you then enter into the grand contest among all fund managers to see who can best serve and protect investors' assets, (and be rewarded according to your standing in this contest.)

I know, this is the idealistic way to look at things. Serving and protecting seem to be what policemen should be doing, not traders. But as in quantitative trading, I think it helps one becomes more successful in one's activities by having a simple guiding principle or model. And it doesn't hurt that in this case, the principle would also be conscience-nourishing!

Wednesday, September 02, 2009

Have you traded 10,000 hours yet?

Author Malcolm Gladwell, in his fascinating bestseller "Outliers: The Story of Success", cites neurological research showing that "10,000 hours of practice is required to achieve the level of mastery associated with being a world-class expert." This seems to apply across many different types of experts, whether they are "writers, ice skaters, concert pianists, chess players ... Even Mozart ... couldn't hit his stride until he had his ten thousand hours in".

Reflecting on my own experience, I have become consistently profitable only after 4 years of actual trading (research alone doesn't count -- real money need to be at risk.) So while the number of hours may not be exactly 10,000, the order of magnitude is about right.

So if your trading has not been profitable, ask yourself this: "Have I traded 10,000 hours yet?"

Friday, August 21, 2009

Using R to Test for Cointegration

Paul Teetor, who guest-blogged here about seasonal spreads, recently wrote an article about how to test for cointegration using R. Readers who don't want to pay for a copy of Matlab should find this free alternative with similar syntax quite interesting.

Friday, August 14, 2009

Interview on backtesting

I have given a 2-part interview (here and here) on the various nuances of backtesting on tradingmarkets.com. Most of the ideas have been covered in my book, but it does serve as a summary of what I consider to be the most important issues.

For those of you who are interested, I may be giving a workshop on general techniques in backtesting in London as well, in addition to my pairs trading workshop. Additional details will be available on epchan.com at a later date.

Monday, July 27, 2009

Are Triple Leveraged ETFs suitable for long-term holding?

Triple leveraged ETFs marketed by Direxion have been all the rage lately. The fund management company says that they do not recommend buying and holding these ETFs. But is there any mathematical justification for this caution?

Before I answer this, it is interesting to note that these ETFs (e.g. BGU is 3x Russell 1000, TNA is 3x Russell 2000) are managed as constant rebalanced portfolios, a concept I discussed before. In other words, the fund manager has to sell stocks (or futures) when there is a loss, and buy stocks (or futures) when there is a gain in the market value of the portfolio, in order to maintain a constant leverage ratio of 3. This is also identical to what Kelly formula would prescribe, a methodology discussed extensively in my book, if the optimal leverage f were indeed 3.

However, the optimal f for such market indices are quite a bit lower than 3. Both Russell 1000 and 2000 have f at about 1.8. This means that since the funds are leveraged at 3, there is a real possibility that sustained losses could ruin the funds (i.e. NAV going to zero unless new capital is injected, which, er..., reminds me of a Ponzi scheme). So I would argue that not only should an investor not hold these funds for the long term, the funds themselves should not be leveraged at this level. Otherwise, it is a disaster waiting to happen.

Friday, July 17, 2009

A free Matlab-to-Interactive Brokers API

For readers who do not want to pay for a commercial Matlab2IB API, Max Dama has put together a free alternative. Domenic has provided some additional sample Matlab codes for trading.

A user of the commercial product that I previously mentioned reports that "My problem with the matlab2ib product was that it did not have a function for all the Active X methods. ( for example the Market Scanners, Real time Bars and Fundamental Data methods are missing). I also had issues when I tried to steam in trades data(I'm not sure if the matlab2ib product allows you to even do this?)." Apparently Max's API has included these methods, though I have not personally tried them.