Showing posts with label momentum chasing. Show all posts
Showing posts with label momentum chasing. Show all posts

Saturday, October 21, 2017

Systematic Trading | Using Autoencoder for Momentum Trading

In a previous post, we discussed the basic nature of various technical indicators and noted some observations. One of the ideas was: at a basic level, most indicators captures the concept of momentum vs mean-reversion. Most do so in the price returns space, but some in a non-linear transformation of the returns space, like signed returns or time since new high/ low. We presented the idea of a PCA approach to extract the momentum signals embedded in these indicators. From there to a trading model, the steps will be to collate this momentum signal (1st PCA component or higher if required) along with other input variables (like returns volatility and/ or other fundamental indicators) to train a separate regression/ classification model (like a random forest or a deep NN).

One of the issues with using simple PCA is that it is linear and hence may not be appropriate to summarize different measures captured across all these indicators. Here we discuss the next logical improvement - a nonlinear dimensional reduction approach using autoencoder.

As discussed here, the new Keras R interface has now made it very easy to develop deep learning models in R using the TensorFlow framework. Here we use this interface to train an autoencoder to fit the same set of technical indicators on NSE Nifty 50 Index as before. The steps involved are relatively straight-forward. First we generate and standardize the inputs (technical indicators levels). Then we build the computation graph.

To do so, first we define the encoding layers (2 hidden layers, the latent coded unit size is 3, to match the first 3 components of the PCA we use for comparison), and two different decoding layers. The two different decoding layers are to  enable us to train the auto-encoder as well as compute only decoding independently.


Next we combine these layers to create the computational graph. One for the encoder only, another for the decoder, and a third one for the end-to-end autoencoder, that we will actually train.

The rest of it is standard. We define a loss function to map the input to the output, measuring mean squared losses, and train the model. The training is done on data till 2013, and test set is since 2014 till present. Once the training is done, we can use the encoder and decoder separately to generate a dimensionality reduction of the input space and vice-versa.

The output of the dimensionality reduction is compared with the PCA. As it appears from the correlations, the PCAs are almost one-to-one mapped to the three latent dimensions in the hidden layer generating the encoding. So the encoded layers are orthogonal in our case, although this need not be true always.

V1
V2
V3
PC1
1
-0.3
0.2
PC2
0.1
-0.2
0.8
PC3
-0.2
-0.9
0.5

The scatter plot below captures the same, but also highlights the some non-linearity, especially the first component of PCA vs the first latent dimension from the autoencoder.


From here the next step is obvious, replace the PCA factors inputs in the momentum trading model in the first paragraph with these latent dimensions from the autoencoder and re-evaluate. This will capture a richer set of inputs that can handle non-linearity and hopefully performs better than linear PCA. Here are some results what other reported (opens PDF). Here are some more (opens PDF) on the using autoencoder for cross-sectional momentum trading. The entire code is available here.

Wednesday, January 4, 2017

Systematic Trading: Back-testing Classical Technical Patterns


Following up from my last post on systematic pattern identification in time series, here is the part on identifying and back-testing classical technical analysis patterns. This is based on the classic paper by Lo, Mamaysky and Wang (2000). The major improvement added here lies in defining local extrema in terms of perceptually important points (as opposed to the kernel regression based slope change technique proposed in the paper). In my view, the kernel method can be too noisy and much less robust with real data.

The R package techchart has two functions for identifying classical technical patterns. The function find.tpattern will sweep through the entire time series and find all pattern matches. It takes in the time series as the first parameter (an xts object), a pattern definition to search for, and a couple of tolerance parameters. The first one is used for matching the pattern itself. The second one pip.tolerance is used for finding the highs and the lows (perceptually important points) on which the pattern matching is based. These tolerance numbers are in terms of multiple of standard deviation. Below is an example:

x <- getSymbols("^GSPC", auto.assign = F)
tpattern <- find.tpattern(x["2015"], tolerance = 0.5, pip.tolerance = 1.5)
chart_Series(x["2015"])

add_TA(tpattern$matches[[1]]$data, on=1, col = alpha("yellow",0.4), lwd=5)



Apart from returning the pattern matches, it also returns some descriptions and characteristics of the match. As below:

summary(tpattern)
## ------pattern matched on: 2015-06-23 --------
## name: Head and shoulder
## type: complete
## move: 1.49 (percentage annualized)
## threshold: 2079.52
## duration: 57 (days)

While this is useful, you already must have spotted the catch. As this function looks at all available data at once to find a pattern, future prices influences past patterns. While this is useful for looking at a time series we need another function for rigorous back-testing. The second function available, find.pattern is to be used for this purpose. This function takes in similar arguments. It returns matched patterns. The match is based on either a completed pattern, or a forming one. A forming pattern is extracted by bumping the last closing price up or down by 1 standard deviation in the next bar and checking if it completes the pattern.

The process of identification of pattern is decoupled from the process of extracting patterns from the data - as proposed in the Lo et al (2000). The pattern defining function in the package is pattern.db.  This follows a similar implementation as here by Systematic Investor Blog, with some added features. The implementation of pattern.db in the package techchart contains some basic patterns - head and shoulder (HS), inverse head and shoulder (IHS), broadening top (BTOP) and broadening bottom (BBOT) - the default in the above functions being HS. However it is trivial to define any pattern (as long as it can be expressed in terms of local highs and lows) and customize this pattern library.

With this framework, it becomes quite straightforward to test and analyze pattern performance, run back-test on pattern based strategies and/ or combine patterns along with other indicators to devise trading strategies at any given frequency. 

Here is a straightforward implementation of such a back-test, using the quantstrat package. The strategy is quite straightforward. For a given underlying, we scan data for a head-and-should (or inverse head-and-shoulder) match. Once we find a match, we enter a short (long) position if a short term moving average is below (above) a long term one. Once we enter in to a short (long) position, we hold it for at least 5 days, and exit on or after that if a short term moving average is above (below) a long term one. We apply this strategy across S&P500, DAX, Nikkei 225 and KOSPI. The chart below shows the strategy performance.

The thick transparent purple line is the average performance across these underlying indices.  The performance metrics are as below. It also has (not shown here) a strong positive skew characteristics. 

Performance metrics
S&P
DAX
NKY
KOSPI
ALL
Annualized Return
0.0566
0.0536
0.0678
0.0528
0.0639
Annualized Std Dev
0.1233
0.0982
0.1413
0.1205
0.0692
Annualized Sharpe (Rf=0%)
0.4591
0.546
0.4797
0.4382
0.9234

Not spectacular, but nonetheless interesting. The R code for this back-test is here. Apart from techchart, you would need to install quantmod and quantstrat (and associated packages) to run this. Please note, running this pattern finding algorithm can take considerable time depending on the length of the time series and system characteristics.

Sunday, November 29, 2015

Time Series Momentum Strategies | The Spirits Within - Part V

This is part of a series on time series momentum. Previous post on this are:

1. Part-I: Time Series vs Cross-sectional momentum
2. Part-II: Nature of linear time series momentum filters
3. Part-III: Types of sizing function
4. Part-IV: Strategy characteristics for random walk with a trend

In the last post we analyzed characteristics of a generic momentum strategy in case of an underlying following a random walk with a known trend. In this post we look in to the returns characteristics in case when the underlying is an auto-regressive process, specifically AR(1).

Once again, we assume the sizing function $\Psi$ is linear. Asset return $r_t$ is given by $r_t = \phi.r_{t-1}+\sigma.\epsilon$, where $\epsilon\sim N(0,1)$. Remebering that for linear function the expected return of the strategy is expected value of the signal times return, we get
$$E(R_t)=E(S_tr_t)=E(\sum_{s=t-k}^{t-1}(w_sr_s)r_t)=\sum_{s=t-k}^{t-1} w_s E(r_sr_t)=\sum_{s=t-k}^{t-1} w_s \gamma_s=\Sigma^2\sum_{s=t-k}^{t-1}w_s.\phi^s$$
Here $\Sigma^2= \frac{\sigma^2}{1-\phi^2}$ is the unconditional variance of the process. This makes the expected return sensitive to both the weighing scheme, i.e. the signal, and also exponentially sensitive to the auto-correlation coefficient $\phi$. Notice how this differs from the previous case. The higher order moments like variance and skew also vary exponentially with $\phi$ as in the figure below (left-hand one).


Everything (expected return, strategy vol, skew) increases with $\phi$, however increase in return is more than vol hence Sharpe improves as $\phi$ increases. While comparing across different types of positioning function (right hand chart above), the change in the Sharpe ratio is not very significant at reasonable values of $\phi$. The major difference comes in terms of higher order, i.e. skew and excess kurtosis. Again, we see that double-step and sigmoid present a competing choice between Sharpe ratio and positive strategy skew, perhaps with a bias to double-step in this particular case.

The influence of the weighing scheme on the strategy performance of course will depend on the underlying process. Here for the AR(1) process, the shorter the MA lookbacks, better the performance, to the extent that for very large MA (like 50/200) the strategy skew even turns negative (not shown here). Similar to the results above for varying $\phi$, the expected return and the strategy skew is more sensitive to the weighing function than strategy volatility.

The optimization objective here again would be to estimate the process parameters, but perhaps hoping for higher accuracy than the case for a known drift random walk. This is not only because the performance sensitivity is an order higher than before, but we also need to optimize the weighing function (i.e. the signal) which depends on the underlying process parameters. In previous case, we would be happy to have confidence on the sign of the drift term, ignoring the accurate estimation of its value. But in this case, with a given risk/reward budget, we need much more accuracy in the estimated value of $\phi$. Nevertheless, as far as positioning is considered, we again see sigmoid and double-steps are good competing alternatives, with a favor for sigmoid for a implementation with linear instruments and double-steps for non-linear instruments.

Monday, November 9, 2015

Time Series Momentum Strategies | The Spirits Within - Part IV

This is part of a series on time series momentum. Previous post on this are:

1. Part-I: Time Series vs Cross-sectional momentum
2. Part-II: Nature of linear time series momentum filters
3. Part-III: Types of sizing function

In this post we look in to the returns characteristics of a generic time series momentum (TSMOM) strategy. We have the expressions for the returns and moments for the previous post. We here consider two cases of the behaviors of the underlying asset - one where the asset behave like a Gaussian random walk, and in the second where the asset returns are autogressive (of the order 1).

Gaussian Random Walk: Let's assume our sizing function $\Psi$ is linear and the underlying asset is a random walk. That is asset return $r_t$ is given by $r_t=\mu + \sigma.\epsilon$, where $\epsilon\sim N(0,1)$ is Gaussian noise. In this case we can find the expected return from a TSMOM strategy as below
$$E(R_t)=E(S_tr_t)=E(\sum_{s=t-k}^{t-1}(w_sr_s)r_t)=\sum_{s=t-k}^{t-1} w_s E(r_sr_t)=\sum_{s=t-k}^{t-1} w_s (\gamma_s+\mu^2)=\mu^2\sum_{s=t-k}^{t-1}w_s=\mu^2$$
Here $\gamma_s$ is the autocovariance of underlying returns at a lag $s$. We obtain the results using the facts that $\gamma_s=0$ for $s\neq0$ in our particular case, and also that $\sum_{s=t-k}^{t-1}w_s=1$ by design. This is a case of strict TSMOM strategy in the sense all $w$ are positive. The result is intuitive. The position size is proportional to the expected return $\mu$ and so is the return on this size, hence the square of $\mu$ term. Note, this result does not depend on the exact type of signals, as long as the weights are positive and adds up to one. Similarly we can show the volatility (square root of variance) of this strategy is proportional to $\mu\sigma$. Figure below shows simulated results for different parameters


As we can observe, the expected returns and strategy volatility is as discussed above. The skew of the strategy is positive and increases with decreasing $\mu$ (till a certain threshold) and increasing $\sigma$. Excess kurtosis increases with decreasing $\mu$. The signal function $S$ is a 10 vs 50 period simple moving average cross-over signal. Since for this special case of random walk, all the individual terms under the summation evaluates to the same expression for all terms (this is true for all moments), the underlying signal function parameters (i.e. simple vs. exponential or 5/10 period vs 50/250 period) do not influence the performance.

However, the positioning function $\Psi$ will influence the performance. The above results are for a linear function $\Psi=S$. Below is the performance comparison for different types of $\Psi$.



As we can see, there are variations in statistical characteristics across different choices of $\Psi$. The sigmoid function behaves similar to the linear function we have already seen. This is expected, for example, sigmoid can be made to resemble a linear function (with position cut-off) with appropriate choice of parameters. In general for the random walk case, binary function will show similar expected returns and variance as the underlying itself and little skew or excess kurtosis, Compared to both, linear will have higher skew due to higher potential position on the extreme. Sigmoid usually will show a reduced expected return (but maintaining the Sharpe Ratio more or less).

However, the double-step shows markedly lower Sharpe and higher skew (in spite of the position limit). It has a lower vol but an even lower expected return makes the Sharpe lower overall (compared to the benchmark linear case).  The higher skew comes from the sharp increase in position at a relatively lower threshold of signal (compared to, again, a linear function). Also higher the threshold $\epsilon$, higher is the skew.

So in the case of random walk with deterministic drift, the optimization problem is rather trivial. The underlying signal function does not affect the strategy performance much. That includes the type of the signal and the parameter space of the signal function. The choice then reduces to finding appropriate positioning function $\Psi$. Usually the linear is NOT preferred because of potentially very large exposure. Sigmoid is a good choice for position limiting with a higher Sharpe. On the other hand double-step is a good choice for a high skew strategy. Depending on the trading style (confidence in underlying process estimates, along with risk management), instruments (linear or convex) and trading horizon (we will come back to trading horizon later in details), a combination of sigmoid and double-step can deliver the desired mix of Sharpe and positive skew.


Friday, November 6, 2015

Time Series Momentum Strategies | The Spirits Within - Part III

This is part of a series on time series momentum. Previous post on this are:

1. Part-I: Time Series vs Cross-sectional momentum
2. Part-II: Nature of linear time series momentum filters

The second phase of designing a momentum strategy is designing the positioning function $\Psi$. This is the function that converts the signal in to a positions. The common choices are:

1. Sign/ Binary function (i.e. maximum long position allowed if positive signal, maximum short otherwise): The simplest of the lot. Sharp change in positioning near 0 level of signal (ambiguous zone) which can lead to increasing turnover and related costs. $\Psi = Sign(S)$
2. Linear (including constant): Simple, but no limit on maximum position. $\Psi =c S$, $c$ is a constant scaling factor.
3. Step function: Sudden change in direction (although no longer around the ambiguous zone). $\Psi=+1|S>\epsilon, -1|S<-\epsilon$. Here $\epsilon$ is the threshold.
4. Sigmoid function (error function) or tangent hyperbolic filtering: Smooth combination of linear and binary, moving gradually from one to another depending on parameters. $\Psi=erf(S)$, or $\Psi=\frac{-e^{-S} + e^S}{e^{-S} + e^S}$
5. Reverse sigmoid function: Sigmoid with peak sizing in long or short zone. $\Psi=e^{1/2}S.e^{-S^2/2}$



Given this set up, now we are ready to look in to the performance of such a strategy. By definition, the one-period return of the strategy is $R_t=\Psi(S_t).r_{t}$. The expression for one-period mean is as below.
$$\mu = E\left(\sum{\Psi(S_t).r_t}\right)$$
The k-th moment is given by 
$$M(k) = E\left(\sum{(\Psi(S_t).r_t)^k}\right)$$
As we have seen already, S can be (in case of linear filters) expressed as $S_t=\sum(w.r_t)$. Also for linear $\Psi$ we can take the coefficient outside the summation notation.


Wednesday, November 4, 2015

Time Series Momentum Strategies | The Spirits Within - Part II

This is part of a series on time series momentum. Look here for the previous post on this.

Here we focus on time series momentum strategies in a single underlying (as opposed to diversified momentum trading). 

The typical time series momentum trading strategy has two distinct design phases. The first one is generating a trading signal based on some logic applied to the underlying price levels or price returns. This, therefore, can be thought of as a function $S$ converting the underlying prices or returns to a trading signal. The second phase is designing an appropriate positioning function $\Psi$. This accomplishes converting the output from $S$ in phase one in to a sizing or positioning. In many cases, we can have the third phase consisting of risk management. This phase includes putting different types of risk management logic, like stop losses or take profit or we can even club volatility filter under this category. For the sake of practicality and simplicity, we keep risk management out of scope and concentrate on a strategy involving the basic two steps as above - designing $S$ and $\Psi$. The schematic below shows how the price or returns (first terms) flows through these filters to generate a profit or loss number (last term)
$$logP_t \Rightarrow S(logP_t) \Rightarrow \Psi(S(logP_t)) \Rightarrow r_{t+1}\Psi$$
$$r_t \Rightarrow S(r_t) \Rightarrow \Psi(S(r_t)) \Rightarrow r_{t+1}\Psi$$
First set refers to price-based signals, and the second set refers to returns based signal. Here $r_t=(logP_t - logP_{t-1})$ is the one period return. Note we are using logarithms of the prices for filtering, while in most cases (like moving average) simple prices are used.  This for convenience so that we can write the percentage returns as a difference of logarithms of prices. The designing objective is to choose $S$ and $\Psi$ to optimize the performance.

The two most common types of signal designing is either a momentum signal on the returns (RMOM) or a moving average crossover signal (XMOV). An RMOM signal computes a weighted average of recent returns and goes long if they are positive. A simple strategy based on such a signal is to buy an asset if, say the recent monthly return has been positive. A simple TSMOM signal will be as below
$$S_t^{RMOM}=\sum_{s=1}^nw_sr_s=\sum_{s=1}^nw_s(logP_{t-s+1} - logP_{t-s})$$
Here $w$ are the weights and $n$ is the window of the applied filter. A buy signal is generated for $S_t^{RMOM} \ge 0$. Similarly, a moving average cross-over signal tracks two moving averages and signals a buy when the fast one crosses the slow one from below. The moving average signals will be as shown below
$$S_t^{XMOV}=MA_t^{fast} - MA_t^{slow}=\sum_{s=1}^nc_s^{fast}(logP_{t-s+1}) - \sum_{s=1}^nc_s^{slow}(logP_{t-s+1}) = \sum_{s=1}^n(c_s^{fast} - c_s^{slow})logP_{t-s+1}$$
Here $c$ are the weights and $n$ is the window of the applied filters. A buy signal is generated for $S_t^{XMOV} \ge 0$.

Pedersen and Levine (from AQR Capital) have shown that these two are in fact equivalent ways of expressing same filtering. They have even shown that in general all linear filters are equivalent. For example, the equivalent ways of expressing the XMOV signals in equivalent RMOM expression is to compute the equivalent weights as
$$w_s=\sum_{j=1}^s(c_j^{fast} - c_j^{slow})$$
Here are some examples of price level filters mapped back to returns space applying these results.


Here the simple MA crossover is based on a 50 period and 250 period (fast and slow respectively) moving average filters. The corresponding EWMA is designed to have similar filtering (in the sense that the net signal has similar center of mass). Also note that the net signal weights are both positive and negative for the price space, but strictly positive on the return space in these two cases.

So we see that in general, we can represent the signal function $S$ as weighted past returns, in the form of  $\sum{w_sr_s}$, at least for linear filtering and scaling. Next we look at the positioning function $\Psi$.

This covers a significant number of technical indicators (like ROC, MACD, or even normalized momentum filters like CCI, assuming a known and constant volatility - i.e. constant scaling). However, this will exclude non-linear indicators like Aroon oscillator.

Tuesday, November 3, 2015

Time Series Momentum Strategies | The Spirits Within - Part I

This is first part of a small series on some observations on general time series momentum strategies. In this I lay threadbare generic time series momentum strategies with the objective of establishing general theoretical underpinning on the strategy performance and optimization approach.

The class of "time series momentum" strategies are very common and popular among investors. At its simplest, it means buy high and sell low. Or more precisely, buy high (an asset that has recently appreciated) to sell at a even higher price. Similarly sell low (an asset that has recently sold off) to buy back at a even lower price. From this point of view, this is fundamentally different than the value investing paradigm. In other words, any returns generated from these class of strategies should be independent and hence should represent an independent risk factor to the investors.

Most of the theoretical interest in momentum investing started with the classic paper by Jegadeesh and Titman in 1993, where they found strong evidence of momentum profit. Further research followed these interesting observation since then. However, what is described as momentum in this case is usually termed as cross-sectional momentum (XSMOM). This is fundamentally different than what is usually understood to be time series momentum (TSMOM).

An XSMOM strategy looks at the relative performance of a basket of assets, and invests in the winners and shorts the losers. The buy/sell signal is generated from relative performance of different assets (cross-section) within a given time interval. On the other hand, a TSMOM strategy looks at past performance of an asset, and buys if has been a winner, or sell otherwise. A TSMOM strategy may or may not involve a basket of assets, it does not depend on a basket crucially for the strategy implementation (unlike the XSMOM which is meaningless without the context of a basket). When a basket is used for a TSMOM it is for diversification and risk management.

This fundamental difference in construction shows how the performances of these two strategies can be similar and different. For sake of comparison, let's assume in both cases we have a basket of two assets. As it is evident if we indeed have strong correlated changes in asset prices (past performance predicts future), then both strategies will perform, as we will be buying and selling the right assets by construction. However, even if we have a change in the momentum, if there is an increase in dispersion of the asset performance (e.g. winner becomes losers, but losers become even more so - not a complete reversal, as in winners become losers and losers become winners) then the XSMOM will still perform. Similarly, even if we do not have strong auto-correlation, but persistent trends the TSMOM will perform better.

It seemed to me the first major theoretical insights in to TSMOM strategy was presented by Moskowitz, Ooi and Pedersen in 2012. The paper also captures the essence of the above paragraph, by breaking down the sources of profits in XSMOM and TSMOM strategies, as follows (in terms of one period expected returns):

$$E[r_{t,t+1}^{XSMOM}] = \frac{N-1}{N^2}tr(\Omega) - \frac{1}{N^2}[l^T\Omega l - tr(\Omega)] + 12\sigma_{\mu}^{2}$$
$$E[r_{t,t+1}^{TSMOM}] = \frac{tr(\Omega)}{N} + 12\frac{\mu^T\mu}{N}$$

Here $\Omega$ is the covariance matrix, $\mu$ is the mean returns vector, $\sigma_{\mu}^{2}$ is the cross-sectional variance of the means, $N$ is the number of assets in the basket and $tr()$ is sum of the diagonals. The above expression clearly shows the points made in the previous paragraphs. The TSMOM returns is driven by auto-covariance and strength of the drift terms. Where as XSMOM, in addition to auto-covariance, also depends on cross-variance (dispersion) and cross-variance of the mean returns (dispersion, again), but not particularly on the strength of the mean returns. These results are valid for linearly weighted basket (linear in returns), but in general give good guidance.

Tuesday, June 30, 2015

Back-Testing Systematic Strategies Part 1: A Flow Chart Based Approach

Systematic trading brings on a certain discipline and the advantage in terms of risk management that comes along with it. And with today's cheap computing power, it is available to anyone. A proper back-testing is almost always at the core of a systematic trading strategy. A wisely designed back-test is the litmus test for an investment hypothesis. At the same time, it helps in sizing the trades and risk management given a particular ability and appetite to take on risks.

However, for the individual traders and investors who has developed market insights over the years, but not very familiar or eager or able to get their hands dirty with coding, running a back-test with dependable results can be a huge headache. Here I try to show how we can approach this problem in a structured manner.

The very essence of back-testing is defining some rules of trading (buy or sell signals) and risk management (stop loss or take profit etc.) based on a market price (of the instrument we are trading) and probably some more indicators (which can be as simple as a technical indicator, or a complex function defined by the user). The R package quantstrat handles this problem in a very well defined manner and split the functionalities in different blocks or modules so that designing a back test, running the strategy and analyzing the data all becomes simple and modular. We take a simple example of running a intraday momentum strategy on the National Stock Exchange flagship index NIFTY50 to highlight this point.

The core strategy we want to back-test is simple. Every trading day we wait for a certain amount of time (or price bars) after the market opens to see the initial momentum. If the open is positive (negative) beyond certain threshold, we then go long (short). Before the end of the trading day we square-off the position. Optionally we can also add a stop loss and take profit target. 

Thinking backwards, the back-test will be driven by our buy and sell trading rules and square-off rule. In turn they will be generated based on:

a) if the opening price criterion meets the condition and 
b) if we are at the beginning of the day, and finally 
c) if we are approaching end of day to place square off. 

This in turn means, the signals that need to go in is: 

i) a price move indicator for positive move
ii) a price move indicator for negative move
iii) a start-of-day indicator and 
iv) an end-of-day indicator

We would need i) and iii) both to be true (logical AND) for a buy signal, and ii) and iii) for a sell signal. The indicator iv) is enough to drive square-off. Schematically, the entire scheme looks below


And if we can design this schematic logically, in terms of a simple, easy to understand flow chart as above, it becomes rather straight forward to develop the underlying codes to run the strategies. As an example I ran the strategy for 2-minute bar of intraday data since 19th of May to 26th of June, and here are the results with different combinations (with 100 units for buying or selling for each trade).



For the underlying strategy without any stop-loss and take profit targets, the trade positions and evolution of profit and loss looks as below (click to enlarge).


And once we run the back-test, we can further delve in to the details and analytics, like the chart below which plot the Maximum Adverse Excursion plot for the base strategy
In short, a very simple strategy, quickly designed in to a simple flow charts. The back test shows it really works, and also throws lights on how to size the trades given your investible capital and risk tolerance.

We will further follow up on how to translate any back-testing in to a similar flow chart, which enables quick and reliable back-testing.

(Those who are interested in the underlying code, it is available here.)

Sunday, April 26, 2015

This is NOT Nuts, Where is the Crash? (II)

With dollar index on record highs, emerging market equities (except, of course, China!) getting bullied around on fed hike scare, and as the Greek saga continues, investors around the world are beginning to worry about risk trades. Especially equities and high yields. IF I am not mistaken, the latest Bloomberg investors survey points to that direction. Well, it seems we need not worry, not as yet! The Risk-On is going still very much strong.

I take the major equity indices around the world along with treasuries and internal sovereign ETFs (iShares) as well as high yields, and run some PCAs. The correlations as below.


The first one is obviously the risk-off/ risk-on factor. The second one is more like a fixed income allocation factor. The last one is domestic (US) vs international factor. We pick up the first factor and run it through a regime switch model (a Hidden Markov Model). The results below. The figure shows S&P Performance (orange) vs. the probabilities of different states we may be in. State 3 (bottom-most in black) represent Risk-On, state 2 (middle in black) is the Risk-Off state, and state 1 (top most in black) can be construed as Risk-Moderation state for lack of better words. As we can see, we are very much in Risk-On (click image for bigger picture).



Given the general nature of flows, esp smart money flows, chasing asset price momentum, we can say that much touted crash/ correction is a bit further away in to the future. Interestingly, similar analysis for other factors along with the assumption above means, for domestic investors, US fixed income is becoming increasingly less attractive, and foreign FIs more so.

__________________________________________________________________________________
1. if you are wondering about the title, part I is here)
2. data from 2010 onward, analysis and plots by depmixS4 and Quantmod package on R 

Tuesday, September 9, 2014

The Scottish Referendum Trade: For AUld Lang Syne

Should one short the sterling pound betting on the Scottish Referendum? Even after the current sell-off?

Of the 4 million voting population, a 2% difference between the YES and NO means betting on 80,000 odd votes. The variation in expected turnouts may be more than that!

On the other hand the cable is naturally under pressure. With softer inflation and easing pace of recovery it is very hard to reason for a steady upward movement. The rates differential with the US has narrowed. The terms of trade does not point to any particular richness or cheapness. 



And as of latest data, the market positioning is favorable. The CME data shows the net speculative position even at the start of September was net long. So unlike yen and euro, not much pressure for a sudden short squeeze. 

If the vote is YES, there will be a large move for sure, at least in the short run. May be a sell-off worse than 5%. With a NO it can rally easily 3% to the 1.66 levels. So the odds offered will be a 37.5% chance of a YES vote.

The opinion polls put the odds at 50-50. But opinion polls are typically unreliable. Going by the wisdom of the crowd on public betting sites, the mood swung a bit recent time. The current going rate for the YES vote prices it at 32%. 

Either the wisdom of the crowd is skewed, or the market is wrong. Upside? quote a lot with the shock supported by the sell-off trends. Downside? Even if GBP goes back to the recent peak (which is, by the way, highest since 2008), it is 6%.

Pay off is asymmetric!

Tuesday, April 22, 2014

Markets: Speculative Positioning Update

Below some selected charts for global speculative positioning (compiled from CFTC CME, CFTC CBOT, CFTC CMX and CFTC NYMEX data). The red line is the asset price levels (on RHS axis) and the blue lines is the outstanding net speculative interest






The theme is, as usual, momentum chasing, with most asset positioning closely tracking the performance. The exception to the rule is VIX. Of the notable changes, the wheat and the corn have seen a strong turn around in the short interests as is the case for Aussie dollars. The opposite was seen for gold, which has a serious reduction in long interest after peaking in March. Equities remain marginally net short, except Nikkei 225 where the long interests strengthened in recent times. Commodities mostly strengthened. And rates remain mixed, with strong short interest in the belly and otherwise for the short end as well as long end.