Saturday, January 14, 2017

Markets | Quick Take on Presidential Inauguration

Next week's Presidential Inauguration is a much awaited phenomenon - for general public as well as for the financial markets across the globe. Dow 20K is mostly an arbitrary mark for a market index designed for pre-computer era (and some equally arbitrary Theoretical Dow has already crossed the benchmark). But it appears the entire market is somewhat directionless at present. Since the election, it has made certain assumptions on the policies of the upcoming government and has shown some very strong move across asset classes (see here, here and here). However, we still have very little in terms of concrete policy direction to rely upon. The latest press conference did not quite live up to the expectation of details on policies. A strong guidelines on future policy in the inauguration can provide a new direction to the market one way or the other. And this can kick start the next phase in the market.

The charts below show the market impact of Presidential inauguration since the post-war era (excluding first term of Barack Obama, which was in many ways an outlier). The X-axis is the number of business days from the inauguration day. The chart on the right shows normalized moves of the S&P 500 Index from 3 month before to 3 month after for each inauguration. The chart on the left shows the median line and the uncertainty around it. It appears more often than not, the markets usually rallies in to the inauguration, experiences a slight correction going in to the exact date, and tops out  around 1 or 2 weeks after the actual date before picking up its own course. (Note we have not corrected for the usually positive trends for the markets in general and hence we should not focus much on the trends here but change in the direction of the trends instead.) However we have quite an amount of uncertainties around this. Looking closely at the right hand side chart we see this pattern was more or less followed by around 10 or 11 times out of last 17 cases. (The legends on the right chart are initials of the presidents followed by a digit signifying the term, if required)


Overall positioning-wise, we have nothing extreme in either way. Post elections the leveraged funds (CTAs and hedge funds) and asset managers have increased their long (from CFTC reports). The dealers have become slightly short the markets - but all well within range. On VIX, however the dealers and asset managers remain long against the leveraged players.


This, and trend analysis of the recent intraday movement of S&P 500 suggests the street (i.e. the players who hedge) is mostly long gamma at this point. See the chart below (and see here for interpretation). This means a large sell-off is quite unlikely in the short term. On top of this, we have the asymmetric scenario on the policy clarity. If President-elect Trump does announce clear guidelines on his policies, this will likely confirm the market assumptions (very low chance of a major negative surprise) and market can have the next leg of rally. On the other hands, impact of rhetorics and vagueness will most likely be muted as there is always the next time. This suggests a long positioning for the equities. However the case of dollar is quite different. We have a very strong long dollar positioning from the leveraged players and any disappointment can be felt quite hard in the dollars.


Finally, while you can't miss the obvious market reaction to Trump's win, it is fairly easy to miss - what I think the most dramatic - real economy reaction. The NFIB small business optimism and outlook went over the top following the election, much more than the overall business outlook and optimism measures. The charts shows the standardized measure and the spread. 


I think in itself, this is quite significant. Historically, we have only two similar situations when the business indicators were significantly positive and small business optimism outperformed overall measures. Once was during the recovery of early 90s and secondly during the recovery of early 2000s. While we have too few data points to draw any statistical conclusion, in both cases we had sustained economic improvement and overall positive market performance. Of course small business optimism does not necessarily mean it will be realized, nor what is good for small businesses is also necessarily good for overall markets. But perhaps we have too many people bracing for a crash now?

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.

Monday, December 26, 2016

Macro | 2017 - The Year Ahead

2016 has been the year of surprises - The Brexit, the US Presidential election, the Italian referendum, the massive de-monitization in India, the Nobel prize in literature - you name it. But perhaps the real surprise was how the markets shrugged off each of these supposedly to catastrophic events.

As discussed earlier, this year has been the year of the dollar. The chart below on the left compares volatilities across asset classes in terms of cumulative daily moves greater than 1.5x the daily standard deviation. The dollar has been the clear winner. But also notice the sharp pick up in rates (US 30y here) late this year, reflecting the sell-off after the US election. The chart on the right shows the reversal and continuation of trends across asset classes during the year. The solid performance of risk assets after the sell-off early in the year, in spite of the dollar rally, increase in yields and continued weakness in the Chinese Yuan, has been nothing short of unexpected.


Going in to the next year, however, much of it depends on the performance of the US economy - more specifically the continued strength of the private consumption components and the much expected revival of the investment expenditure. The charts below show what to expect in each of these going in to 2017. A simple linear model points to the strong dependence of the house prices, real rate and labor productivity. The biggest risk to this component of GDP from rising rate is the house price, which has been strong in 2016. The upside risk is of course a much awaited improvement of the productivity (without a runway inflationary pressure).


The investment expenditure, on the other hand, is largely driven by the inflation (NOT real rate, based on this empirical AR(1) model) and expectation about the economy (here represented by the Conference Board leading Index for the US). This part will be crucially determined by the policies of the new administration. The built-up expectation about fiscal spending and its impact on keeping the US growth engine running I think is a bit over-rated. In fact fiscal stimulus in an economy with tight labor market can be more inflationary than expected. The biggest upside may possibly be in the private investments front, which has been running remarkably low for a recovery compared to past episodes. A judicious mix of policy can change this. An improvement in tax regime and infrastructure spending may make US assets attractive not only for domestic, but also for overseas investors. On the other hand, the storm kicked up over trades and foreign policies can be unsettling for long term investments. This is too early to conclude in either way - but this will definitely be the major source of risks, either good or bad. And if this hypothesis is true, this will mean a decoupling of the movement of rates, risk assets and dollars, conditional on no extraordinary increase in inflation or inflation expectation.

The last bit about contained inflation is the base case scenario. Over-all 2016 has seen global inflation picking up in the second half of the year. This to a large extent is driven by the recovery in energy prices and commodities in general. We are still to see any thing on the core inflation that will be any cause of concern. In fact global core inflation is down marginally in the second half in 2016, with notable exception of China. The medium to long term inflation forecast remains stable. The recent rally in inflation break-even markets, while impressive, is coming off from a very low level. We have discussed before the weakening relationship of wage pressure and headline inflation. Nevertheless wage growth is least of any concerns. We do have decent growth in wages in the US, but they are hardly extraordinary compared to pre-crisis periods, and elsewhere globally it remains subdued.


2016 has also been remarkable in at least two other aspects. First, we have seen a definite improvement in global PMI, not only limited to the US anymore. And also the significant contraction in US (negative) current account balance since the post-crisis QE world has now turned a corner and we have a marginal expansion in US current account deficit again. This is all the while with an expansion of Chinese current account surplus along with strong Euro area balance and contraction in current account surplus in petro-dollars economies. If the recent recovery of oil prices sustain, we will see the last bit changing in to positive territories again. That leaves the post-crisis anomaly of the very large Euro area surplus. The global imbalance in trade (and alternatively net savings) is shown the chart below on the left. During the 2000s, the US consistently ran an increasing current account deficit and a shrinking interest rate differential (see the right hand chart below, weighted rates differential to Euro and Japan economies). The dollar more or less followed the suit, weakening during most part of early 2000s. If we assume the QE is more or less done for the ECB and in 2017 we will focus back on tapering in the base case scenario, then it is hard to see that rates differential widening any further. Add to this the massive current account imbalance of the Euro area, and 2017 might as well be the turn-around year for the Euro, instead of the consensus long dollar trade (barring political accidents).


Finally, one of the biggest anticipation in 2017 is the great asset rotation, investors fleeing the bonds universe from the rising rate fear and piling in to equities. Again, there is hardly a strong case for that. Firstly, the demographics in the developed world does not allow a strong return to equities. Secondly, the fear about overseas official accounts dumping treasuries is largely unfounded - primarily most of them have been snapped up by the private sectors, and if we have steady energy prices we will see a lot less selling of treasuries by the petro-dollar economies. China, of course remains vulnerable with a steady outflow, but the outcome is unexpected here. A large dumping of treasuries by China, driven by PBoC's need to supply dollar demand in the domestic economy, will mostly be a risk-averse move and will have the opposite effect on US yields than what a large sell-off might suggest (i.e. a flight-to-safety rally instead of a bonds sell-off). As far as the US households are concerned, they started the great rotation a while back already - as the chart below show.



Overall, we can conclude from above that the major macro drivers for 2017 will be 1) US house prices and US fiscal and trade policies 2) Euro area economic indicators, especially credit impulse 3) The uncertain role of the emerging market economies in face of rising rates and dollars and finally 4) The re-balancing of global excess savings. We should expect a limited rise of rates and inflation (and inflation expectation). Also risk assets face no immediate strong head-winds yet as we expect the upside risk to bond yields and inflation limited. Finally, as we near the end of monetary activism and divergence, going forward we will see a higher de-correlation among asset classes. The major tail risks remain the Chinese economy - where expected risks of accident are low (but with a large impact of course). Among idiosyncratic risks, the UK economy may be vulnerable to a dragged-on negotiation on Brexit, which also potentially may have some mirror impact on the Euro area.

Given this, here we list the top macro trades for the coming year. Note these are the major themes and ways to express them, not a fire-and-forget strategy to be executed on the first trading day of the year.

Economic Theme
Market Impact
Trade
US Policy Regime Shift – pro-business (tax friendly), pro-fiscal (infra spending) with a risk of foreign confrontation
Macro: Consumption (and employment) has limited upside, the main upside lies in investment pick-up. Downside for house prices and trades
Market: Selectively positive for equities, negative for rates, Limited upside for dollars.
  1. Pay USD rates against GBP
  2. Long equity options with knock-out on lower rates
  3. Forward vol around (1y5y5y or similar) through vol-triangle, or simply 1y5y vs. 1y10y vol spread to protect against unexpected inflation/ sharp bear flattening.
  4. Rates receivers with lower rates knock-in for hedging economic shocks (long equities hedge, positive carry on upper left on forwards levels)
European/ Global   Recovery
Macro: higher rates, higher Euro (against USD and GBP) and higher inflation – with political surprise downside for Euro Area. Normalization of EU trade balance.
  1. Long Euro FX calls with knock-in on higher rates
  2. GBP vs. EUR inflation breakeven tightener (pay GBP breakeven)
  3. Opportunistic rates steepener convergence
Brexit Implication
Unsustainably high priced-in inflation in UK. Equities so far priced-in only sterling weakness (FTSE in dollar terms sold off same as GBP since Brexit, this does not incorporate any weakening of the economy)
  1. Short FTSE 100 quantoed in euro vs. SX5E or beta-weighted SX7E (highly correlated to Euro rates)
  2. GBP vs. EUR inflation breakeven tightener (pay GBP breakeven)
China Put
A flare up of Chinese crisis. Chinese market prices more controlled, than dependent countries
  1. China rates payer vs AUD
  2. Short EM bonds (especially if you see a strong dollar rally ahead of us)
EM underperformance
Dollar strengthening, and economies closely linked to dollar following the rates moves
  1. Buy dollar against EM CCY basket
  2. Short EM bonds (especially if you see a strong dollar rally ahead of us)
Euro Area Crisis Hedge
Reversal of peripheral spread tightening
  1. Long Germany break-even vs. Italy (follows  closely the CDS spread)
Run-away inflation cheap hedge
The (unlikely) scenario of central banks losing control or way behind the curve. The idea is while normal inflationary pressure will push real yields, runaway inflation will force monetization, given the debt-to-GDP ratios of major economies.
  1. near-OTM rates payers vs. inflation, against far-OTM inflation caps against rates.

Have a great year ahead!

Monday, November 28, 2016

Macro | How Sustainable is the US Dollar Rally

The dollar rally that started since the conclusion of US presidential election shows not much signs of abatement. 2014 was the year of crude oil, when the fantastic sell-off in crude set much of the moods prevailing in the world economy - from equities to rates. In 2015, this slowly turned over to dollar, partly through the surprise CNY depreciation, and later through Fed rate hike expectation. And without any doubt, despite all the noises around the Brexit and Italian referendum votes (early Dec), the dominating factor for risks is again US dollars. The figure below shows a quantitative look at the cross market risk drivers using Minimum Spanning Tree methodology (based on correlation). It shows clearly the dollar is in the center of the cross market driving force. A very similar situation to what we had back in 2013, but more concentrated role for the dollars to set the market sentiments. We already had a not-so-quite riot in rates following the dollar strength post election. The emerging market currencies and equities have taken significant beatings. And top houses are calling for this dollar strength to be one of the top trades in 2017. Naturally it begs the question how much leg is still left in this dollar rally.

To take a long-term look, the dollar rally is by no means extreme. In nominal terms the broad-based trade weighted dollar index is near its historical highs. However, when we compensate for the inflation differentials between the US and its trade partners, the rally is well within the historical range (still 13% off from the 2002 peak) - as the chart below shows. Note the rally in dollar since 2014 has been almost equal for the real and nominal exchange rate - 17% vs 20%.


But while this rally may not be extreme, it may not be sustainable either. A large part of the recent dollar strength has been on the back of expectation of US policy change, specifically a possible fiscal stimulus. The economic argument behind is that a fiscal stimulus, coupled with a budget deficit will increase interest rates and hence the exchange rate. In fact this is what was observed during early 1980s in the US (although it has not much support from observations in other non-US advanced economies). The actual mechanism is far from clear. There are extensive studies on budget deficit reduction and its impact on exchange rates, but reverse studies are rare. Theoretically, the direct impact (of increasing budget deficit) goes through the interest rate and asset return channel above and lead to a higher exchange rate (as demand for higher interest assets goes up among foreigners). On the other hand, increased budget deficit can increase the long term inflation expectation and hence expectation of future dollar depreciation. The second part of the policy is trade - which is basically a tightening pressure on the US current account deficit - if President-elect Trump follows though his promises. Typically for the US the current account in recent history has been driven to a large extent by demand for financials assets from overseas investors. This means a tightening of current account will have to be matched by reduced demand for US financial assets by foreign investors, resulting in a currency depreciation now (and possibly an appreciation later). In fact the post-crisis dollar weakness has resulted in a significant tightening of current account for the US already. A further sustained tightening in general may not be great for either the US or global economy. The other possible factors, i.e. the overall demand (or GDP differential) or real rate differential with major trading partners are relatively straightforward, an increase in both leading to a stronger dollar.

Looking in to the above set of arguments empirically, we run a quick vector auto-regression estimates with real dollar exchange rate, real rate differential, current account (% GDP), budget balance (% GDP) and GDP differential as endogenous variables (differential with GDP-weighted Euro area and Japan data representing rest of the world). The results are as shown in terms of impulse response - i.e. response of dollar real exchange rate for unit positive move in budget balance (FD), current account balance (ca), real rates differential (rates) and GDP differential (GDP). It seems at least for our data (spanning 1995 to 2014, quarterly), Trumps policy of budget deficit (negative fd) and tightening current account (positive ca) has off-setting impact for dollar real exchange rate. In fact there are good chances the current account tightening impact (negative for dollar in near term, positive long term) can overwhelm. An increase interest rates may make US assets attractive among foreign investors, but without matching trades the flows in to those assets will be difficult to sustain. Among other drivers, while inflation in US has been steady, including wage growth, we have seen some early signs of a come back of inflation in the Euro area. The main thing to look out there is the pick up in Euro area credit growth after a stall start of this year.

Given this ambiguous impact of policy, and hopefully a declining need for policy divergence and a head-room for trade-weighted dollars of only ~13% to reach all time high in real terms, it does not look like the dollar rally has much room left. one of the surprise trigger can come from ECB and/or BoJ in December, with QE in Europe still priced in. And the Dec Fed hike - which is almost a certainty now - will act to defuse this rally. 

Interestingly, while from the emerging market point of view, the recent dollar rally was kind of risk-off, it was hardly so for Euro. Euro - which has lately became a funding currency like the Yen, sold off steeply. Arguably there was not much positioning to blame either, so this makes it a very interesting move. The Euro area as a whole has accumulated a huge current account surplus in its glut for savings in the post-crisis period. A substantial change in trade relationship with the US may start to unravel that. If you are positioning for the consensus Euro dollar parity, think again. 2017 may see a major reversal in Euro instead dollar.

Note: all data from the St Louis Fed FRED database.

Saturday, November 5, 2016

Markets | The Trump Trade?

Keynesian beauty contest is an interesting concept that shows a group of perfectly rational agents trying to predict the outcome of an event may not converge on the most expected case, provided their risk and reward depends on what most others think. I think something similar happens in the markets around a big event. Rarely it is clear what are the implications of different possible outcomes of such events. In such a scenario, a trader's immediate pay-off depends on how good he is at predicting market reaction (as opposed to the actual implications). As a result collectively the market ends up reacting in some ways that very few people may actually believe.

Next week's presidential election is such an event. There are strong evidences that economy has significant impact on election outcomes. however the reverse result is very weak if any. Performance of a large globally connected economy depends on more things beyond the control of the Oval Office than we give credit for. However the markets seem to have already formed an opinion and trading according to the poll results in recent week. This is not only the US market but across the globe. The common denominator is an expectation of underperformance with a republican win.

The consensus is more or less a status quo with a democratic victory and large uncertain changes with the republic candidate in office. Honestly, I think it is too early to say what will be the policy changes as we hardly have any clue on specific policies apart from election promises. For example it is usually considered republican victory will be good for defense stocks. However if Mr Trump carries out his promise on cutting down on NATO, will that necessarily be the case? He promised to unwind trade agreements. But sure there will be something to replace it, will that be very different than the existing one, and will that have really any significant impact on trades, prices and job? Or may be you should buy Apple? - he is sure to threaten EU to withdraw the taxation case and make America great again! My personal take is Mr Trump promised things, but post election (if he wins) it will be hard to deliver on many of them except in a much run-down version. Hence in the base case, sooner than later, we focus back on things like earnings and economy and inflation once the initial reaction is over.

However, the market is close to pricing in a crash scenario for an outcome favoring the republican candidate. The VIX (and volatility of VIX) are tad shy of last August peaks. The implied skew and (near-month) implied correlation in S&P 500 are racing sky-wards (and interestingly with a quite flat vol convexity, i.e. high skew and very low smile). There is a high amount of uncertainty. 

And if you are planning to take decision (being flat is one of them), I have already written about how to generally think about positioning under uncertainties before. If you are a hedger, you know what you need to do - that's quite it. And if you are a speculator, after all the analyses and mumbo-jumbo, basically you have to choose a side (rally or sell-off) and stick to it. And the only things that matter are:
  1. what is your expectation and how that looks from risk-reward already priced in the markets and 
  2. How to optimize your responses in case you are wrong.




The first one is commonly understood. At present the markets are definitely pricing a large sell-off. This is in the background of decent economic news and improving global PMIs. Technically most markets across the globe has or on the verge of confirming a bearish signal (see chart above). The asymmetric pricing in the downside suggests there are large price move expected, but at the same time it makes the risk-reward unattractive compared to the upside. And based on the past history in S&P which has breached a technical support recently, the distribution of near term returns favors the upside statistically (albeit with a rather large uncertainty spread around that). The chart shows the historical price distribution after such technical breaches (categorized in to three types of technical formation - megaphone, triangle and channel, and whether the existing trend was ascending or descending, and also if the breach is of resistance (up) or support (down))1. We are in a down breach within an ascending megaphone (see the figure above).



As far as the second point is concerned, if you are positioning for downside and it turns out wrong, your responses are limited if you assume it will be a relief rally, (not a sustained one). Alternatively, if you are positioning for the upside and if you are wrong, you will have plenty of opportunities to react. We will sure enter a period of high volatility and there will be plenty of trading opportunities.

So it appears purely based on the second criteria, a long risk positioning is preferred2. Of course this assumes the outcomes are fairly priced from criteria one and you do not have any strong view on either outcome.


Note: 1) This is based on systematic technical analysis, for details see here, for code page go here. You can select or de-select series on this interactive chart
2) this is not an investment or trading advice, do your own due diligence, form your own opinion. See the disclaimer page.

Friday, October 28, 2016

Macro: The Quiet Riot - Continental Version

For the past few weeks, the fixed income market has seen a significant change in moods.

The earliest trigger was in the JGBs market in late July, then it was the Gilts in late September following a pause from BoE. This week it definitely felt like the Bunds. Treasuries are down too from July highs, but in a much gradual fashion compared to the rest.

Now while we do have individual explanation (with the 20/20 hindsight) for all these (BoJ steepening chatter, Brexit, ECB QE rumors and, of course, Fed hike expectation), these moves signals some fundamental changes common across the markets as well. For one, this sell-off in rates is markedly different that recent large moves or the 2013 taper tantrum in terms of the accompanying movement of the inflation expectation. This is the first large sell-off in rates where the real rates (I used 10y yield less the 5y swap breakeven rate) were stable. Clearly the common thread has been inflation expectation - led by the Sterling inflation market, in response to a weakening currencies. But this was not limited only to GBP. Backed by the strong recovery of the commodity prices and oil, inflation markets across regions rallied, recovering from the bottom in Q1 this year. Even the Euro inflation is  flat on YTD basis after this recent move.
However, it is still too early to say if this points to an inflation scare. We are far off from seeing the white of the eyes of inflation. Large part of the recovery in inflation is driven by commodity prices which just came off multi-year lows. With over-capacity in many sectors, and a new cost/ supply equation for oil (see here too), there is no strong case for the commodity rally to overshoot substantially from here. On the demand side, apart from the healthy wage growth in the US, things are not significantly better. UK is still trying to figure out the consequences of Brexit. The collapse of the credit impulse in the Euro area late last year is yet to recover and Japan seems increasingly stuck.

The suddenness of the move suggests a large driver of the sell-off may be positioning, especially in Euro and GBP. Bunds open interest on Eurex were near historical high since 2008 before the selloff. This was definitely not helped by a rather tight-lipped Draghi on the last ECB. ICE Gilt positioning also indicated asymmetry with position build-up after Brexit. For core rates, this means the recent sell-off will stabilize as the pressure from positioning is diffused eventually. However, it is clear that we are approaching near the end of the era of quantitative easing. The next big move in rates will not be triggered by Fed. It will be the policy announcement from BoJ in Nov, followed by ECB's decision on QE in Q1 next year. Fed is priced in, and with all probabilities, will carry out a measured hike in December. It will be mostly a non-event.

What is rather interesting is how the current monetary policy plays out for the curve. It is clear we are increasingly approaching the end of QE-topia, with some central banks moving to normalize, and some still leaving considerable liquidity in the system and trying to lean on the next lever. This apparent divergence in the first order (the level of rates) is leading a convergence drive in the second order (the yield curve slope). BoJ is actively seeking to steepen the curve to alleviate concerns of the banking sectors, among other things. ECB will be glad to have the Euro area curve steepen back. The Fed is allegedly getting in the same business. The latest round of rates sell-off, unlike most before in recent time, was mostly a bear steepening move. Unfortunately, steepeners are not as juicy as they used to be in terms of carry a couple of years back, but still this is the trade to be in for the medium term - either in absolute term or cross-markets.

On the equity side, contrary to general view, this is not at all negative. Inflation recovering from current levels shows strength of the macro drivers. In fact in recent years, S&P 500 has shown more asymmetric correlation to inflation expectation than outright rates itself (see chart below). The thick tail on the right hand side has been dominated by inflation downside (i.e. correlated sell-off in equities with collapse in inflation expectation). A recovery in inflation expectation should be positive, at least initially, and ultimately uncorrelated to equity performance (runaway inflation is still a distance myth). This is especially true given the strong commitment from the Fed on its intention of slow paced hikes.
The S&P appears to be in a consolidation state - in a typical triangle formation, before the next leg (usually up from here).


The downside for equities from here is in fact event risks, and not macro. The US presidential election is one -although apparently the market does not care. Italian referendum is another - and again the history does not make a strong case for it either, if you go by the off-hand manner in which market digested the outcome of recent southern European election outcome.

Saturday, October 22, 2016

Systematic Trading | An R Package for Automated Technical Analysis

This is an R package for automated technical analysis and some ground stuff for some pattern matching algorithm I plan to build. This is available at github - you can directly install it from github or you can fork or download. Currently it has three functionalities - 1) perceptually important points 2) change points for time series with linear deterministic trends and 3) automated technical support/ resistance/ price envelope identification (useful for back-test, but I have not found the time yet). It has also an undocumented module for technical pattern identification, which is in fluid state. Please note the is in early version and features/ data structures may undergo substantial changes in later version. I copy paste the R vignette below.


Techchart: Technical Feature Extraction of Time Series Data The R package techchart is a collection of tools to extract features from time series data for technical analysis and related quantitative applications. While R is not the most suitable platform for carrying out technical analysis with human inputs, this package makes it possible to extract and match technical features and patterns and use them to back-test trading ideas. At present, the package covers four major areas:
  • Perceptually Important Points (PIPs) identification
  • Supports/resistance identification (either based on PIPs or the old-fashioned Fibonacci method)
  • Change point analysis of trends and segmentation of time series based on underlying trend
  • Identification of technical envelopes (like trend channels or triangles) of a time series

Perceptually Important Points

PIPs are an effort to algorithmically derive a set of important points as perceived by a human to describe a time series. This typically can be a set of minima or maxima points or a set of turning points which are important from a feature extraction perspective. Traditional technical analysis - like technical pattern identification - relies heavily on PIPs. In addition, a set of PIPs can be used to compress a time series in a very useful way. This compressed representation then can be used for comparing segments of time series (match finding) or other purposes. In this package, we have implemented the approach detailed here.
spx <- quantmod::getSymbols("^GSPC", auto.assign = FALSE)
spx <- spx["2014::2015"]
imppts <- techchart::find.imppoints(spx,2)
head(imppts)
##            pos sign   value
## 2014-02-03  22   -1 1741.89
## 2014-03-07  45    1 1878.52
## 2014-03-14  50   -1 1841.13
## 2014-04-03  64    1 1891.43
quantmod::chart_Series(spx)
points(as.numeric(imppts$maxima$pos),as.numeric(imppts$maxima$value),bg="green",pch=24,cex=1.25)
points(as.numeric(imppts$minima$pos),as.numeric(imppts$minima$value),bg="red",pch=25,cex=1.25)

The function takes in a time series object (in xts format), and a tolerance level for extreme points identification (can be either a percentage or a multiple of standard deviation). It returns an object which has the list of all PIPs identified, marked by either a -1 (minima) or 1 (maxima), as well as the maxima and minima points separately as xts objects

Supports/ Resistance

Supports and resistance levels are very popular tools for technical analysis. The function find.pivots implements a couple of ways to identify supports and resistance levels for a price series. Using the option FIB will produce a set of Fibonacci levels around the most recent price point. The option SR will run an algorithm to find co-linear points along x-axis (horizontal line) to find levels most tested in recent times. A set of levels as well as xts representation of the lines defined by them are returned
spx <- quantmod::getSymbols("^GSPC", auto.assign = FALSE)
spx <- spx["2014::2015"]
sups <- techchart::find.pivots(spx, type = "FIB")
summary(sups)
## supports and resistance:
## next 3 supports:1982.249 1936.355 1890.461
## next 3 resistance:2130.82
sups <- techchart::find.pivots(spx, type = "SR", strength = 5)
summary(sups)
## supports and resistance:
## next 3 supports:2043.688 1992.551 1895.028
## next 3 resistance:2070.407 2111.588

Price Envelop Identification

Price envelopes features are an integral part of technical analysis. For example technical analysts look for features like trending channel, or ascending triangles etc to identify continuation or breakout from current price actions. The function find.tchannel identifies the most recent such envelopes using an implementation of the popular Hough transform algorithm in image processing, along with some heuristics.
spx <- quantmod::getSymbols("^GSPC", auto.assign = FALSE)
spx <- spx["2016-01-01::2016-09-30"]
tchannel <- techchart::find.tchannel(spx,1.25)
tchannel
## name: channel
## type: neutral
## direction: 0
## threshold: NA
quantmod::chart_Series(spx)

quantmod::add_TA(tchannel$xlines$maxlines[[1]],on=1, lty=3, col="brown")

quantmod::add_TA(tchannel$xlines$minlines[[1]],on=1, lty=3, col="brown")

The function returns an object with parameters of the envelopes found (if any), as well as the xts representation of the envelopes lines