Tuesday, August 8, 2017

Markets | Trading the "Bond Bubble"

One of the most confusing conundrum in recent time has been the curious case of stubbornly weak inflation and upbeat economy with low unemployment.

The US GDP number, while not spectacular, has been solid. Atlanta Fed GDP-Now picked up significantly in recent time. The consensus forecast for medium term GDP (2018) also improved from the start of the year and now stands at 2.3 percent. Unemployment rate remains near record lows, below pre-crisis number. According to JOLTS surveys, both quit rate and job opening rate matches or betters the pre-crisis cyclical highs. Even the relatively more pessimistic Fed labor market conditions index has improved significantly from the lows of early 2016. But both market and survey based inflation expectations are going the other way. The 5y treasury break-even inflation came-off ~40bps from highs of early this year and now stands at 1.65 percent. Similar is the story for break-even swaps markets. To match, the medium term consensus inflation forecast has come down from 2.4 percent early this year to 2.2 percent. The fall is even steeper for 2017 forecast, from 2.5 percent as recent as April, it is now at 2.10 handle. And this does not appear to be driven by oil or commodities. Both Brent and WTI have been range-bound since mid of last year. Even the set-back in general commodities prices (see Bloomberg Commodity or CRB index) early this year is now on the path of recovery. The Phillips curve is either flat, dead or was never there.

This conflicting development seemed to have a win-win impact on major asset markets. Instead of the fabled great rotation, we have seen strong money flows in both stocks and bonds - blame it on the re-balancing of portfolios, or general optimism.

The stock market benefited from solid economy and strong earnings, with valuation also supported by low rates. But the positioning remains cautious (with a correction in the gamma positioning as well).

A more interesting development is happening in the bonds markets. The bonds markets seem to have sided with the low inflation view - that no matter what the Fed does - inflation, and rates, are not going anywhere anytime soon. The over-all positioning remains solidly in the long territory. But the peculiarity is in the strong flattening bias build-up. Early this year we saw a massive swing in long maturity bonds positioning, from extreme shorts to moderate longs. This was presumably driven by the built-up and subsequent unwinds of the Trump Trade. As a side-effect, this has resulted in the extreme flattening positioning on the street. It appears everyone is positioned for a low pace of rate hikes from the Fed, and anchored low inflation expectation - resulting in a yield curve flattening. Last few times we had this kind of extremes (early 2010, mid 2012, around just before Taper tantrum and start of 2015) we had a very strong steepening that bloodied all these speculative position well and good.

Most of the players in the markets are already wary of overall bonds positioning. Some are calling out a bond bubbleSome are ready to take the opposite view. If you are in the markets to trade and not for punditry, it is hard to take a strong view. This extreme positioning in the curve provides a cheap (in terms of risk to reward ratio) way to position for a bonds sell-off. Or forget bursting the bubble, even a Fed balance sheet normalization can be the trigger. It is not at all certain balance sheet normalization will lead to increase in term premia and long term yields. But most theories say so. And if the Fed decides to hold short term policy rates during this normalization, this steepening can play out in both bull or bear scenario. And honestly, nobody has any clue how the Chinese are going to change their treasury buying patterns after the National Congress in the Autumn. If the current premier is able to stamp his authority, as generally expected, this may mark a definitive shift in policy from GDP growth target to economic stability. That, in turn, will have far reaching ripples for global asset markets.

At current level, the US curve is the flattest among all major currencies (except 5 year vs. 10 year area where JPY curve is flatter). A steepening in USD rates is a highly asymmetric trade - the trade to position for a bond bubble, whether you believe in it or not.

1. Data source: ICI for funds flow data, CFTC commitment of traders for positioning data (latest 1st August)
2. Steepening position is implied from short end (2 year and 5 year) and long end futures positioning, expressed in equivalent (approximate) duration at 10 year point.

Sunday, June 25, 2017

Off Topic| Wide and Deep Learning in R

R is an excellent environment for quick and dirty data science. I am a R user and obviously a bit biased, but between Python and R, R has always had the edge for data visualization and quick hypothesis testing. If you do not find the latest and greatest methods of bleeding edge analytics somewhere available already within the strong R package ecosystem, it is more or less safe to assume it does not exist anywhere else either. And forget Python, the IDE from R Studio is perhaps the best IDE across any development platform (although the Visual Studio perhaps has a better debugging interface). But one area where R has been weak is in machine learning, especially in the deep learning area. And with the explosion of interest (and fad?) in deep learning, this has become quite a glaring gap.

But hopefully not anymore. We already have Google's TensorFlow available in R for a while. But to be honest, it did not have much feel of R in it and looked like a deprecated version of the Python release. However, very recently the R Studio folks released a R support for the excellent Keras high level API, with back-end of TensorFlow. This feels like R (with some quirk like in memory modification of objects) and works like a charm. Although it runs on top of a local python platform, the package exposes pretty much all the functionalities Keras support.

You will already find a list of examples in their site here. Here is to add a basic example of how to set up a wide and deep learning network. This involves creating two separate learning network. The wide one has only one layer (effectively a logistic regression of sort). The deep network is created separately. The output of two is combined (concatenated) in a final decision layer (this is slightly different architecture than the TensorFlow example). This is run on the usual Census Income data-set. The error rate for this set up is around 16 - comparable to other methods officially reported.

Tuesday, June 6, 2017

Markets | Positioning For The UK Election

UK goes in to elections this week. Since the surprise announcement in April, the polling has narrowed quite a bit between the two major parties. (See chart below - although note a large part of Labour gain has been at the expense of smaller parties, especially UKIP). However although the markets had a sharp initial reaction to the announcement, the moves subsequently have been more cautious. The outcome of the election is touted as determining the direction of Brexit negotiation. And markets appear to be waiting to assess the situations once the results are out. However, what the market will focus on in Thursday evening is not only the UK's divorce from the European Union.

Looking past the Brexit, the major differences between the Tories and Labour campaign is their respective stance on tax and government spending. If conservatives have their ways, it will basically continue the status quo, without any significant change in taxation or spending.

On the other hand, the labor plans to increase taxation (focused on corporates and top earners) as well as infrastructure spending. The National Transformation Fund with a corpus of £250b proposed by the Labour compares to a £23b National Productivity Investment Fund of the Tory government. The net effect is an increased need for borrowing, put at 45b estimates by the Tories. The other major campaign difference will perhaps add to this bill. The Labour maintains a so called "soft Brexit" approach, and a change in government in London may actually increase goodwill in Brussels. But Labour's negotiation aims also implies the UK may actually end up footing a substantial Brexit bill.

Put together, these means increased issuance of Gilts for a Labour government compared to the Tories. So in an unlikely scenario of a major Labour win, all the market forces and economics fall nicely in place. Gilts will sell-off on the back of fiscal plans - along with a steepening of the curve. Sterling pound will rally, supported by both the new Brexit stance and a rising yields. Equities will sell off, triggered by both taxation and a rallying pound and rising yields. For a strong conservative win, the impact is mostly in market sentiments than any dramatic departure in economics.

As we see from the charts above, the correlation in Tory polling vs. GBP and Gilts have mostly switched to negative off-late (and to rather positive territory for Labour). These correlations implies a Tory win will have some downside impact for GBP. But strong win may even see a small upside driven by a reduced political uncertainty before the economics kicks in. Gilts have little scope to respond vigorously, facing the inflation pressure on one hand and a more than expected Dovish BoE on the other - marginally positive for Gilts (yields go down). Equities will perhaps shrug off all of it.

That leaves us with the scenario of a Labour-led coalition government. This will in general hurt the market sentiments, with a higher chance of a addled up Brexit negotiation and potentially another election around the corner. This will be a sort of risk-off moment for UK, with sell-off in pounds and equities and a rally in gilts. This will also be a shock event - as at present the betting markets prices in a 90+ % probability of a Conservative majority. Assigning some reasonable probabilities to various outcome, the pay-off matrix looks like below. And it suggests a short GBP position before the election.

Position-wise we have seen a large reversal of positions in futures (as per CFTC reports) after the election announcement - a large decrease in net speculative shorts in Sterling pound. On the other hand, the currency options market shows a significant increase in negative skew pricing (demand to protect from a sterling crash). In fact the GBP 1 week 10 delta risk reversals is near the highs around the Scottish referendum in 2014 (although much less than the highs reached around Brexit referendum). So it appears we have some options positioning (or at least demands) - indicating a position switch from futures to options. Assuming most dealers in the FX markets will have the opposite position, this adds to a negative bias on Sterling.

Saturday, May 6, 2017

Markets | VIX - Waiting For Godot

By now everyone and their cats are aware that volatility across markets and asset classes are low, been so for a long time, and shows no signs of reversal. VIX, the US market benchmark vol index is around it's historic lows. The MOVE Index - the bond markets benchmark from BofA/ML - is no better. CVIX - an FX benchmark from Deutsche - is doing a bit better but nothing assuring. People have punted, hoped and feared a come back of volatility, but so far we have not seen any sustained sign of it.

The reasons and the expectations from analysts come under mainly two flavours. The first narrative is that volatility is artificially suppressed by big league volatility sellers (speculators, but more importantly those ETFs folks and systematic risk factors people). The second narrative is market in general is going through a hopeful optimistic patch supported by central bank puts. Both groups believe volatility is going to explode sooner or later. According to the first narrative, a potential driver is a random shock, that will force re-balance in ETFs and risk factors strategies and will amplify the move. The second version is we are just a few bad economic prints or some geo-political mis-steps away from a runaway volatility.

While both of these narratives have some merits, none of them is either sufficient or complete. Or even useful for any practical purpose. There are different opinions, but I tend to side with the arguments from risk factors people (like AQR) that this line of arguments vastly over-estimates the impact of risk factors portfolios. And it is hardly fair to blame some folks for selling vols in a steep roll-down scenario as we have these days (we have written about it before). On top there is certainly some influence from street positioning. As we have written about before, for a long time now, the dominant positions of the big hedgers (read big banks and market making houses) in the markets have been long gamma, putting a stabilizing effect and pinning the vol down. The second "complacency" narrative appears less plausible, but of course cannot be ruled out.

But irrespective of which one (or may be even both) you believe in, none is useful to take a position in volatility. Essentially the argument is: volatility is trading in a distorted way and we need an external event to set it right. It is cheap since such an event will surely come some time in future. Unfortunately, by definition, we cannot predict much about the timing of an unexpected external event. And presumably you do not have the luxury of an infinite stop-loss on the bleeding you will have while you wait for that vol exploding event to materialize.

In fact the only predictable statement to make about the direction of volatility is: when the rates go up, VIX will follow. And here is why.

To start, note that although the VIX is near historical lows, it is not cheap. The realized has been lower. And the second fundamental thing to note that in the post-crisis world, the volatility has transcended its status as just a "fear gauge" and has become an asset class in its own right. And in this world of unconventional monetary policy and low rates, volatility has become intrinsically tied to the level of rates. The chart below captures this point.

We talked about this point way back in 2012 (from bonds markets point of view). When you treat volatility as an asset class (where selling volatility is a surrogate carry strategy) it becomes clear to see the connection. Consider an asset allocator who has an option to either sell volatility and collect the premiums, or buy some equivalently risky carry product, e.g. a high yield corporate bonds portfolio.

To make apple-to-apple comparison, we can think of a hypothetical "volatility bond". Given the existing spread of risky (BBB) bonds to treasury, we can deduce the probability of default of such an investment. From this, we can hypothesize a volatility bond, which consists of selling an out-of-the-money (OTM) call spread and put spread on S&P 500, each 100 point wide. The strike of the short options are such that the probability (implied from volatility) of them ending up in the money is equal to the probability of default of the high yield portfolio above (worth 100 in notional). In both cases the maximum we can lose is $100 (note in the case of short vol strategy, only one of the call or put spread can be in the money and exercised against us). So the yield from the high yield portfolio, and the premium collected (let's call that volatility yield) are comparable returns from portfolios with comparable risks. The chart above shows the yields from these two roughly equivalent portfolios. As we can see, in this rough approximation, the vol yield has in fact been higher than comparable BBB yield through out the post-crisis period, and moved in steps. The relative value before the crisis was unbalanced. It would have paid to buy OTM options spreads, funded by a high yield portfolio (anecdotally, there was an equivalent popular trade there during that time, but in the wrong market - the infamous Japanese widow maker). But at present the markets are pretty much in sync with each other and appear efficient. Far from the "distortion" argument in the narratives above. The only way the vol can rationally go up from here is if the general risk portfolio yields also go up. That can happen in two ways. Either spread to risk-less rates (like treasury) increases (signifying a risk-off event like in the narratives above). Or through a secular rise in rates - which basically takes us back to Fed and inflation. As argued in the last post, pretty much everything we can expect now hangs on future inflation path. The results are outcome of an approximate analysis. We obviously ignored some important issues (like skew and convexity of these deep OTM strikes) and made some shortcuts (a digital set-up is more appropriate than a options spreads as in here). We also missed a bit more fundamental point here, which is correlation. S&P 500 is a much broader index than the high yield universe, and the comparison above is more appropriate as the market-wide correlation goes up. As the correlation goes lower, we can afford to sale closer to the money options spread in S&P to retain the same riskiness in the portfolio, thus making the volatility yield even higher. And as we have it, the correlation (again see the last post) is down off late. But the main point remains unchanged - Vol is low but NOT cheap (although last few points in recent time in 2017 points to some relative cheapness). Perhaps it is a good time to stop complaining about low VIX prints and watch those HY spreads and inflation development carefully instead. All data from CBOE website/ Yahoo Finance/ Bloomberg Monday, May 1, 2017 Macro | Cross Asset Correlation Update The markets seem to slowly leave behind the massive focus on fiscal impulse following the US presidential election, and the inordinate amount of stress and optimism about the US dollar rally. This is already reflected at least in terms of asset price behaviours, if not media and analysts focus yet. Cross asset macro drivers for 2017 YTD (based on first factors extracted from principle component analysis for each asset class) looks much like H1 of 2016, which saw a cautious rally in risk assets following the early stress period - albeit now it comes with reduced influence of oil prices and volatility on risk asset prices. This stands markedly different from the H2 of either 2015 or 2016 - which saw a pick up cross asset correlation (with very different outcome, a risk-off move in H2 2015 and a risk-on rally in H2 2016). The MST charts below captures this dynamics pictorially. Among the risk assets, DM equity factor shows increased positive sentiments to rates (i.e. increased yields leading to rally). Inflation has become more important for DM equities as well, while FX has virtually no influence. For EM equities, the latest trends has been a slight de-sensitization to rates and FX movement, although they remain significant. The credit factor also picked up its correlation to rates (and FX, which is mostly influenced by EM credits part), while retaining correlation to inflation. This makes the rates and inflation path the most important determinants for risk assets at present - at least from Developed Markets equity investors' point of view. Markets will always react (or over-react) to tax cuts expectations and presidential elections. But we are now, it appears, back to the basics. On this fundamental note, we have seen some recent encouragement in global inflation space. The left chart below shows GDP weighted CPI inflation (global top 20 economies as well as Developed Markets within that). Since the recent bottoming out at start of 2016, we have seen a secular rise in inflation, which is more pronounced for the DM case. However, the core inflation scenario (not presented here) is far from running hot. Core inflation in the US and China have improved from 2015 lows, but much less dramatically. Only in the case of Euro area this has been solid (from very low levels). One the other hand, global credit growth (right chart below) appears to have topped out in a secular manner. On the positive sides, the wage growth in the US (not shown here) has been encouraging and sustained. If we consider these points, in the context of extraordinary monetary accommodation that exists across the globe today, we should be more hesitant to conclude we are heading towards a definite normalization anytime soon, in spite of strong sentiments. The rates market seems to agree. We have seen inflation recoveries in 2011 (remember the ECB hike mistakes) and also in early 2014. It was a misfire in both cases. A weakening credit impulse and barely normal inflation in the face of extraordinary monetary stimulus represents a global demand which is far from recovered. This makes the case for removal of these extraordinary monetary measures very difficult - most policy makers are still biased to err on the upside inflation naturally. That is unless we see the whites in the eyes of inflation - in which case, it either may be too late, or have to be too harsh and steep. For now, the forward looking inflation measures (both market based like break-even inflation and model based like Cleveland Fed now-cast) remain stable without any sign of worrisome upward pressure. This means the risk assets will largely avoid negative reaction by a possible June Fed hike (market probability of 67% as of date priced in). The key risk in this regard remains any (mis-)communication or premature taper on the central bank balance sheets. All data from St Louis Fred Database Saturday, March 25, 2017 Markets | The Most Peculiar Positioning Build Up Since US Election Last week's S&P sell-off was apparently a big news. We had some serious analyses why it happened like here and of course the usual noise about end of Trump trade and reflation trade. Also the indomitable cottage industry of the permabears quickly felt a sense of vindication. However, the real surprise was why it took so long for S&P 500 to suffer a 1% down day. If we have only one 1% down day since October (roughly say 100 trading days), it is equivalent to an approx 7% annualized vol. VIX has been near record low, but at the 12-13 handle, looks quite rich given this 7% realized (or a bit over 8% if the standard deviation of daily returns is used to calculate the annualized vol). In fact the realized volatilities are very very timid and just barely off the historical lows. In this light one the most interesting development that I suspect few has noticed is the curious build up of S&P option positioning. CFTC publishes the participant-wise positioning data at both futures and combined levels. The combined data is calculated by adding the futures equivalent option positioning (delta equivalent) to the futures data. So the difference between these two shows us the net option positions in delta equivalent terms. And as the chart below shows, it has never been more peculiar. Among the major categories in CFTC reports, asset managers at present have a historically large short positions in options, against the dealers and the CTA/ leveraged money managers. This is a remarkable build-up of positions since the US presidential election. It is interesting to note the usual trading incentives of these major players. The dealers are mostly market makers and their positions are in general reflective of other players' views. Leveraged/ CTA funds, to a large extent, are momentum driven. The asset managers on the other hands perhaps represent the most discretionary part, although most of them will be long-only players. In fact they as a group have built up a combined long position after the US election results - no surprise there. Along with this particularly interesting short build up in options space - quite unexpectedly. The large short delta equivalent option positions from asset managers can be built in two ways. Buying puts - which is a common hedging strategy for the asset managers, or selling (covered) call - which is again a very standard income strategy. But their impact on the market dynamics are quite different. We do not have enough information above to see which one is more dominant. So to do that we look at what the behavior of S&P 500 price itself tells us. From the chart above, we see the dealers positioning mirrors that of the asset managers. If the asset managers are mostly long puts, that will mean dealers are short puts and hence short gamma. On the other hands if the asset managers are net short delta equivalent in options through short calls, the dealers will be net long gamma (long calls). And since the dealers, as market makers, will tend to run a hedged book - this will lead to some expected gamma signature in the market dynamics. When the dealers are net long gamma, they will tend to sell in a rally and buy in a sell-off (sticky gamma). This will have a stabilizing effect on S&P. The reverse is true when they are net short gamma (slippery gamma), a move reinforcing itself away from stability. We compute an approximate measures of this relationship. First we see the how much the open to low move is reversed by low to close move for each day in a given time period (20 days) for S&P 500. Then we use least square regression to estimate a beta between these two moves. This beta signifies how likely in a given day, a down move will witness opposing flows to reverse it completely or partially. A high beta signifies a large pressure of opposing flow (beta = 1 means all downside move reversed by day end). The major drivers in this reversal will be the dealers long gamma hedging activities and potentially the buy-the-dip or momentum flows from other players (apart from other flows which we assume to have a zero net effect on the balance over a time periods). We call this beta (kernel-smoothed to capture the trend) downside gamma. The chart below shows this juxtaposed with the above positioning data, as well as S&P 500. The interesting thing to note that during the last large short delta equivalent option positioning build up by asset managers (following Brexit), the downside gamma measure actually dipped, signifying a net short gamma for the dealers, and hence long put positioning from the asset managers. The current positioning, following the same logic, points to a large short call positioning from the asset managers. In fact there were some noises around this in February as well. As a result of this, the recent moves in S&P has been remarkably resilient. However as of last Tuesday's (21st March) data, it seems this long gamma positioning is coming off from the peak. Which has also coincided with a reduction in net short delta positioning of the asset managers in the option space. Theoretically, this means we can now expect a pick up in realized volatility in S&P. And it is time to shelve the buying-the-dip intraday strategy till the next opportunity comes. Wednesday, March 22, 2017 Off Topic: A Package to Send Text Messages From R If you often run long processes in R and want to get the results notified to you once finished, but not always around to check it on the terminal, this is a very useful package. Of course one option is to send a mail from R (there are quite a few packages for that). However, this may not be a very safe option if you are running the R process on a remote machine (on the cloud). Most mail packages in R will require you to enter your mail password in clean text. While this is okay for your local machine, on the cloud it is a little bit unsafe. Another difficulty is your R process will have to sign in to your mail account (Gmail for example) to be able to send the message. However, your mail provider can refuse - like Google will, citing an unidentified app access. To bypass that you have to considerably reduce your security option in your mail account - which is not ideal. Texting the message using a third party service like Twilio is a great alternative. They offer a free-tier account (with no expiry as they claim). If you are not a heavy user, my best guess is that will be sufficient in most cases. This package simply wraps the REST API interface from Twilio for the simple text messaging service inside an R package for convenience. All that is needed is signing up for the service and obtain the assigned mobile number, and authentication details and you are good to go. I am not sure about the restrictions on international texts, but this works fine for me for local texts. Results direct to my mobile with insignificant time delay. You can download the package from here. The installation and usage (pretty straightforward) are in the readme file in the repository. Friday, February 24, 2017 FOMC | The Ides of March We have quite a bit of built up anticipation for the March FOMC. The Fedspeak analysis of "Fairly Soon" has been interpreted by most as leaning towards a March hike. Some are even claiming the rates markets are underestimating the probability of a March hike. The chart above shows implied 3-month treasury forward curve term structure since the 2014 (after the highs from 2013 Taper Tantrum). In early 2014 the market estimates of long run equilibrium rates were just about 4 percent. Since then we have come a long way. As we see we have three major clustering of market estimates - one at around sub 2 percent (during Brexit rally), another just above 2 percent (early 2016) and the most common level at just about 3 percent. The sell-off after the US presidential election has just brought us back to this 3 percent level. Coincidentally, after disagreeing with the markets on this long run terminal rate for a long time (erring consistently on the upper side), the FOMC also now more or less agrees with this level. So after quite a while markets and the FOMC seem to have converged in outlook. Given this background, I think whether the FOMC hikes in March or not is now a far less important question than what it used to be a couple of years or even a year back. Before March FOMC, we have a round of PCE (Fed's favored measure of inflation) as well as employment and GDP data release scheduled. Unless we have a major upward surprise, March probably will be a no-hike meeting. And more importantly, given the improving economy, markets are in a much better position to absorb a hike anyways. The US and global inflation are improving, but it is much tamed than the "reflation trades" coverage makes it sound. Inflation was a worry (on the downside) before, now slowly it is ceasing to be so. There are few signs the FOMC is behind the curve as of now. What can really take the market off-guard, is however, the question of Fed balance sheet. If and when FOMC plans to reduce its QE-bloated balance sheet, and how they communicate this point. Hiking is a way of tightening. But a controlled balance sheet reduction is also another way. While the former affect the short term rates more (a bear flattening), the later should be more prone to affect the long end rates (bear steepening). A reason why FOMC may actually opt this is to address the historically compressed risk premia - see the left chart below. Even with the recent sell-off, the risk premia remain at a depressed levels. The short end pressure felt on the back of FOMC moves more or less leaned towards a flattening of the curve than any significant correction of risk premia. While the European and Japanese bonds are trading at super-depressed levels, perhaps it is not entirely to the Fed to correct this. But adjusting balance sheet is definitely a direct way to address this. The most important reason NOT to do this it the unpredictable potential impact. This has the strongest potential to send confusing signal to the market, perhaps resembling a taper tantrum version 2.0. The right-hand chart above shows a quick check to identify the pain points based on the current Fed holdings vis-a-vis supply. The vulnerability is concentrated in the long end, especially if this is adjusted for the duration risk (not shown here). The primary reason this may create unwanted responses is that it is not at all well understood. Balance sheet reduction after a massive QE is a completely new thing for both the Fed and the market. The last FOMC minutes (published last week) discussed this issue explicitly for the first time, if I remember correctly. So it is fair to expect this will definitely come up in the March discussion as well. At present FOMC expects re-investing to continue "until normalization of the level of the federal funds rate is well under way". The most important event for the markets from the March FOMC will be any potential change on this view. Realistically, this can be the trigger that can bring us back to the 4-handle level of long term equilibrium rates we had at the end of 2013. Trump fiscal push blow ups and run-away inflation seems pretty far-fetched at present. The asymmetric positioning here is bear steepening. Similarly on the equity and risk assets side, this can have the most unexpected and damaging impact than a regular FOMC hike. Possibly more than even an adverse French elections. The National Front candidate Marine Le Pen, even if elected as the President against all odds, will find it hard to muster enough support in the parliament to call for a national referendum to leave the Euro area. And even if the referendum is held and a majority votes to leave, it is not clear that will actually be followed through - going by the outcome of the 2005 referendum. all data from Federal Reserve and US Treasury. 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 --------
## 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.