Thursday, December 28, 2017

Markets | Bitcoin - The Hidden Optionality

A lot of things about Bitcoin defy conventional logic. For example, valuation of bitcoin can be treacherous and common sense ranges are a tad too wide for traditional economists or investors1. "Exceptionally ambiguous", so to speak. Then we have confusions as captured in the tweet below.

The attitude of the crypto-currency enthusiasts is best understood in terms of Keynesian beauty contest. It is not important to have a specific valuation in mind to HODL Bitcoin. All you need is your estimates of what others might value it at. It is not important to start using Bitcoin to pay for your morning coffee to realize the dream of replacing fiat currencies. All you need is to believe that enough of other people believe in doing so. The entire thing is a second order guessing game.

Theoretically, this set-up makes for an interesting characteristics of Bitcoin price. Since there is hardly any well-accepted valuation, a sudden rally or sell-off will not see the typical stabilizing intervention we see from value investors in other asset classes. Also since most (if not entire) valuation depends on the collective average of investors' expectation, a rally will see further buying and vice versa. This means the time series of price will show intrinsic characteristics of a momentum strategy.

The chart below captures this feature. The chart on the left shows the empirical distribution of MA(1) coefficients for daily returns for Bitcoin (black) and S&P 500 (red). The MA(1) coefficients can be interpreted as the response to a random shock in price. A series showing momentum nature will tend to magnify these moves, i.e. will have higher response coefficient. As shown in the chart, the Bitcoin response is highly skewed towards the right compared to S&P. The chart on the right similarly shows the response to a previous trends (AR(1) coefficients here). Here again the Bitcoin distribution is skewed towards the right. It even crosses the 1.0 mark, the upper limit of stationarity - turning in to what is called explosive process occasionally2!


The second characteristics of Bitcoin is its fat tails. The chart on the left below shows standardized returns across different asset classes (Bitcoin - thick red, equities - black, FX - blues, gold - gold, commodities - purple, rates - green, inflation - brown, VIX - orange, credits - grey). The peaked value and fat tails for Bitcoin far exceeds other asset classes (closest is the option adjusted spreads of AA credit). The right hand chart shows an easy to understand metric for fatness of tails. This displays the ratios of mean absolute deviation to standard deviation. Since standard deviation is a square root of square measure, it is more sensitive to large tail values than mean absolute deviation. The ratio of them shows the fatness of tails. A lower ratio means fatter tails. As the distribution approaches normal distribution (no excess kurtosis), this ratio approaches 0.8. Here we see by far, the ratio for Bitcoin is the smallest. It also shows strong positive skew.



The above two observation makes Bitcoin quite a bit of unique asset class. Nevertheless, we tried to explore which asset class comes close to it, in terms of time series characteristics. Here is the outcome - where Bitcoin stands among different asset classes based on a few measures:



There are multiple ways of clustering time series. One is "shape-based" - e.g. measuring a geometric distance like Euclidean distance. The top left chart shows the asset class hierarchy based on this measure. Bitcoins in this respect behaves similar to gold - very distinct from the carry assets block (VIX and credits), FX, rates, equities and commodities block. On "structural" measure (bottom left), like based on time series correlation, Bitcoin teams up with the commodities block. Finally, based on complexity or information based models (top right and bottom right), Bitcoin reflects the distribution and fat tails characteristics discussed above and behaves more like AA spread or VIX. On the whole, Bitcoin does not appear to be either digital gold, or a currency at all. It is more like a commodity showing fat tails similar to credit spreads and volatility.

In fact this fatness of tails, along with the momentum characteristics discussed above makes Bitcoin less like an asset class, and more like a derivative. Momentum strategies are comparable to options. Most  momentum trading strategies display two characteristics - many small losing trades and a few big winners. The big winners give rise to fat tails (with positive skew). And those small losing trades can be compared to carry cost of an option (theta cost or time value). This interpretation can be readily extended to Bitcoin as well. The good thing about Bitcoin is, given the upwards trends till date, the so-called carry cost has been positive!

Beyond the economists and valuation experts communities, I suspect most traders understand this optionality of Bitcoin by instinct. You invest an amount you are happy to lose, with a possibility of large upside - this is the optionality of Bitcoin without all these technical details. This says nothing about Bitcoin being a bubble or not. But a long position in Bitcoin in a positive trend (or a short position in a negative trend) is going to act like a long option position. A proper valuation of the Bitcoin, therefore, must include this embedded optionality.


1. For example here is a rather ridiculous attempt. And a rather commonsensical overview.
2. Notice how the S&P AR(1) coefficients distribution gets truncated at 1.0, as it should be for stationary processes

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.

Friday, September 22, 2017

Macro | A Paradigm Shift For India's Retail Investors?

The Indian economy is at an interesting point. We had two large scale policy moves in recent time - the much controversial Demonetization in November last year, and the implementation of (a somewhat rundown version) of Goods and Services Tax regime this year. Early this month, we had the first GDP print following these two major steps. The headline prints came in lower than consensus - 5.7 percentage for Q2 vs. 6.5 (and 6.1 last quarter). This was followed by equally weak Industrial Production release. A stronger than expected headline CPI prints did not help, as this squeezes the room for any rate cuts from the RBI.

A closer look at the GDP data (see component break-down in the chart below) shows some serious weakness. The private consumption part (C) has weakened significantly following the demonetization (the vertical red dashed line). The investment component (I) has been weak for a while (although staged a comeback in the last quarter). Exports growth was not helped by a strong rupee. In last few quarters, government expenditure helped the headline a lot. But the sustainability of this is questionable. We will have the fiscal deficit data out later this month. But the street does not expect anything great.

The story of the IIP paints a similar picture (see chart below, overall IIP, manufacturing, base materials, consumer durable, consumer non-durable, capital goods, electricity, intermediate goods and mining respectively). While demonetization appears to have caused a negative shock, in general most of them peaked out before that, around early 2016 to be fair. The capital goods, which staged a minor comeback since bottoming out in 2014, again resumed the downward trend, along with most (except consumer durable, and to some extend mining).


This is all in a relatively benign global macro scenario. In spite of the Fed taper 2.0 announcement, we have little jitters in the markets. Rates, both global and local, are relatively low and volatility remains subdued. Oil prices remain range-bound. A rally in oil along with a weakening INR following Fed and expected ECB taper later this year can worsen the scope of fiscal stimulus. Most in the business sectors does not expect private investments to turn around before end of this year at the earliest. The investment exuberance back in 2004-06 left many corporates laden with unmanageable debt burden and bank balance sheets with NPA.

In this background of weakening macro story, the Indian equity markets is in a tear. The flagship NSE Nifty Index posted a YTD 21%+ gain, among the best globally and compared to it's own history. The trailing 12-month PE ratio is looking worryingly high. High valuation remains a big concern among investors in this, and most other traditional metrics (a bit better in terms of price to book).

However, comparing the PE ratio to its historical average is not very good way to capture everything that goes on to determine fair price. In the most basic approach, the price of equity is a function of market risk free rates (say the local sovereign bond) and equity risk premium. Following the approach in this paper from AQR, I modeled the BSE SENSEX P/E based on the risk factors - the bond yields as well as the equity and bond volatilities (as in the original paper) along with current account balance as a percentage of GDP (reflecting the fiscal risk of the economy) and spread of bond yields to US Treasury (captures the flow risks). The last two are more relevant for an emerging market economy like India. The time-series shows a marked shift in relationship between pre- and post-crisis era. I fitted the model only on (monthly) data from 2010 onward to capture the recent dynamics. As it turns out, the bond vol has little contribution to market risk premia for India. The bond yield and equity vol shows significant but low correlation, whereas the CA deficit and spread to treasury captures a significant portion of the variance. The chart below shows the fit on this model (adjusted R-squared ~0.72).
According to this model, the PE ratio is only slightly on the over-valuation side - not a cause of great alarm. According to this model, the market was highly over-valued around late 2011, and early 2015. We saw corrections in both cases. Also the under-valued period, early this year, was followed by upward corrections as well. This model does not forecast a large correction anytime soon unless we rally up a lot quickly from here (obvious caveat: these are in-sample results).

But what is most interesting, and perhaps most significant is the recent flows that we have seen in Indian equity markets. Traditionally, the equity markets in India has been shunned by a large portion of retail investors. The experience of scams in 1990s and the melt-downs, once during dot-com busts and another in 2008, did not helped. The foreign portfolio investors dwarfed the domestic flows in cash equities for a long time (although it is a different story in F&O). But since 2014, something changed. The extra-ordinary flows in to the equities markets, led by domestic mutual funds (presumably on the back on retail savings channeled to equities) completely outpaced the foreign flows.
Is this a mass optimism following the 2014 election outcome and equity rally? Or are we witnessing a major shift in the savings behaviour of retail investors in India. The retail money has missed the initial come-back equity rally following the 2008 crash, and a part of the early 2014 rally as well, where the foreign investors made out handsomely. But much of the late rally in Indian equities has gone to the retail pockets. Is this dumb money chasing recent gains? We do not know for sure, but as we argued above, we are some distance away from any valuation melt-down in Indian equities. And the flow signifies the loss tolerance of the retails - who are sitting on some comfortable profits - has quite a bit room before panic. And finally, the weakening property markets and demonetization may have incentivized a permanent change in retail behaviour.

We do not know for sure. But what is the implication if it is indeed a fundamental shift in savings behaviour? As argued above, the macro in India is down, but with policies properly executed, the turn-around can be sharp. If oil remains range-bound and the Fed and ECB do not stray afar from the implied forward curves, we will have little in terms of global shock to upset the local economy. On the other hand, the efforts to put banking sector NPA in shape, along with the full kick-back of the GST regime should significantly improve the badly needed private investments. Add to this mixture this retail savings paradigm shift, and we are looking at the very beginning of a multi-year rally in Indian equity markets.

Wednesday, August 23, 2017

Off Topic | How Not To Discourage Banks from Short Term Trading

Lately we have had a lot of talks about Volcker repeal or replace. Does Volcker rule do what it is supposed to? Is it good or bad, and for whom? There are many issues, lobbying and conversations going on right now. Here is the latest proposal from Harvard Law School:
To achieve the objectives of the Volcker rule, we propose that banks be prohibited from basing compensation on trading-based profits. Our prohibition would encompass both ex ante compensation on trading-based profits (such as contracts or non-legally binding representations that the individual’s pay will be tied to their trading profits) and ex post compensation (such as discretionary bonuses the amount of which set based on a trader’s trading profits). Violations of this rule would result in a fine to the entity, claw-back of the individual’s impermissible incentive pay, and potential criminal liability for intentional violations.
The essence  of the argument from the authors are:
  1. Banks compete in the securities market with other banks and firms to make short term trading profit (the target of the rule). Since this is a zero-sum game, only those banks who are able to attract top traders are able to turn in a positive profit, while others will be discouraged (by potential losses).
  2. Since banks also compete in the labour market - i.e. to attract trading talent, banning profit-linked compensation will force talented traders to hedge funds.

Wham! together, the end result is banks getting second-tier trading talents who must compete against the first-tier traders from hedge funds and will lose money in the zero sum game that short term trading is. Hence banks in general will be discouraged to trade short term at all.

There are some serious issues with this proposals and authors' understanding how short term trading, compensation and banks work in general.

Firstly the way banks and hedge funds make money can be significantly different. A top-tier trader in a bank will not necessarily be a top-tier in a hedge funds. In short term trading, there are three ways to make money - 1) You have superior information of who owns what and who wants to trade which way 2) have a balance sheet advantage - to overwhelm markets or to hold your ground or 3) have superior analytical capabilities (better guts, models AI, whatever for short term price prediction) and/or pure trading skill.

Banks usually excel in #1 and #2 because of their dealing role (may be not #2 much anymore, but also they do not have to cross the bid-ask spread). Hedge funds have limited access to these information and balance sheet advantages, but are supposed to have an edge in #3. Many top traders from a banking set-up fail in a hedge fund environment because of this. The trading and making money work differently.

So even if banks lose out top trading talents to hedge funds, by no means they will lose their edges that they specialize in (more true for OTC-heavy asset classes like fixed income and less applicable for exchange-heavy asset classes like equities). The advantages belong more to the seat than the man (or woman as the case may be) occupying it.

And then the compensation scheme itself is weak. The easiest way to link trader's incentives to performance - where you cannot directly link it to trading profit - is to tie it to job security. Hire top talents with a very high fixed compensation. Prune the second-raters in next cycle. Rinse and repeat. The top talents will be attracted  - if they are indeed better, they will know they can perform. A compensation scheme linked to trading profits is a series of call option on trader's PnL. Tweaking this to high fixed compensation is similar, just a series of digital calls (instead of a vanilla calls), with a knock-out feature (based on trading profit).




 

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.