Pattern matching Cryptocurrencies

Bitcoin, Ethereum and some other cryptocurrencies seem to be in the spotlight again due to their most recent acceleration.
C_y2pGfXoAApvdI

Source: CEOTechnician

Ethereum is up multiples since January. I thought we could take a look at importing Etherum price data in R and then seeing if we can draw any parallels between Ethereum and Bitcoin using the pattern matching algorithm we’ve looked at here before.

But first we will load Bitcoin data in R, since it can be more easily accessed through the Quandl API.

library(Quandl)
library(SIT)
library(quantmod)
library(ggplot2)

BTCUSD = Quandl("BCHAIN/MKPRU",type="xts")
head(BTCUSD)
colnames(BTCUSD)[1] =  'avg_price'
BTCUSD.Avg = BTCUSD[,1]

par(mfrow=c(2,1))
ggplot(data=fortify.zoo(BTCUSD), aes(x=Index, y=avg_price))+
  geom_line(aes()) + scale_y_log10() + ggtitle("Bitcoin in USD (Log10)")


ggplot(data=fortify.zoo(BTCUSD), aes(x=Index, y=avg_price))+
  geom_line(aes()) + ggtitle("Bitcoin in USD ")

bitcoin1

As you can see Bitcoin is undergoing another run-up in prices. It’s difficult to see previous runs in the price, so we will also plot bitcoin prices on a log scale, as to better see the percentage gains.

bitcoin_log10

The price acceleration looks more tame in this view relative to previous ones, but the market capitalization of bitcoin has grown much larger than when it had its initial run.

Lets take a look at Ethereum now. We will pull in data via the Poloniex API, process the JSON object and convert the dates. Finally we will look at the linear and log price graphs.

url_m = 'https://poloniex.com/public?command=returnChartData&currencyPair=USDT_ETH&start=1435699200&end=9999999999&period=86400'

library(jsonlite)
mkt_data <- fromJSON(url_m)


ETH <- as.xts(mkt_data[,5],order.by=as.Date(as.POSIXct(mkt_data[,1], origin="1970-01-01")))
colnames(ETH) <- 'ETH'
head(ETH)

ggplot(data=fortify.zoo(ETH), aes(x=Index, y=ETH))+
  geom_line(aes()) + scale_y_log10() + ggtitle("Ethereum in USD (Log10)")


ggplot(data=fortify.zoo(ETH), aes(x=Index, y=ETH))+
  geom_line(aes()) + ggtitle("Ethereum in USD ")

etheth2

What a run!

Lets take a look at the bitcoin data again and see what the closest matches are for the most recent run up. We will be using code similar to a previous post.

bitcoin_Match1

Using a 63 day period for pattern matching and dynamic time warping, we get these results. The prices highlighted in blue are the most recent prices we are matching, and the prices in red are the 10 closest matches.

matching_new

It looks as though most of the upside in the price gains has already been had, as the forward week, month, quarter returns are all negative. Having said this, there was also one run (Match 5) that had a 1,044.7% run.

In the future, we may look at pattern matching log prices, or cross-market pattern matching, for example Ethereum’s recent price run on Bitcoin’s history.

*Not investment advice

If you are trading this parabolic spike, be careful and always use stops. I found this idealized image of stop placement fascinating. stops

Source: “Stop Techniques – The Implications From Inconsistent Forecasting Skills ” Nordea

Trading the index with seasonal strategies

I recently listened to an interesting interview at Better System Trader with Jay Kaeppel on Seasonality, a topic which I hadn’t done much backtesting on previously.

Jay outlined 3 rules for constructing a seasonal trading strategy on the stock index:
– Stay long the last 4 days and first 3 days of the month (S_EOM)
– Stay long the middle of the month, business days 9, 10, 11 (S_MOM)
– Stay long 3 days before and after holidays (S_HOL)

I’ve recreated these rules on the SPY ETF using R and the Systematic Investor Toolbox with the output below:

seasonal backtest

I’ve showed the equity curves for the 3 strategies separately (S_EOM, S_MOM, and S_HOL) as well as the combination of all 3 rules together (S_C2). A third variation (S_C3) is the combination of all 3 rules with a 200dma risk filter on the SPY itself, that is the strategy will only be long the index if one of the rules is true and the SPY is above its 200dma. Two benchmarks are also on the report: The SPY itself and SPY200, which is the SPY with the 200dma risk filter applied again.

The majority of the outperformance for the seasonal strategy is coming from the End of Month rule. The other two rules increase overall returns slightly but don’t have much of an effect on risk adjusted returns, with the sharpe ratio staying relatively constant. The seasonal strategy with the risk filter (S_C3) has a similar return to the SPY itself, but with half the volatility and nearly one quarter the drawdown. A much nicer ride for your portfolio!

In the future I may explore the impact of transaction costs on the strategy as well as how walk forward testing affects seasonal strategy out-of-sample performance.

Jay recently updated some of the strategies from his book, Seasonal Stock Market Trends, check out the links below for more of his work:
Updating my seasonal trends trading strategy Part 1
Updating my seasonal trends trading strategy Part 2

Pattern matching: a quick look at the last 11 months

John Hussman posted the following pattern on his twitter:

Source: John Hussman’s Twitter

So I thought this would be a great time to see which points in history the Systematic Investor Toolbox pattern matching algorithm would highlight. Instead of looking at the Dow Jones I will use the S&P500 Spyder (SPY). Choosing a window period of approximately 11 months and looking at 20 years of data lets see what happens:

###############################################################################
# Load Systematic Investor Toolbox (SIT)
# http://systematicinvestor.wordpress.com/systematic-investor-toolbox/
###############################################################################
con = gzcon(url('http://www.systematicportfolio.com/sit.gz', 'rb'))
source(con)
close(con)

#*****************************************************************
# Load historical data
#******************************************************************
load.packages('quantmod')
tickers = 'SPY'

data = getSymbols(tickers, src = 'yahoo', from = '1950-01-01', auto.assign = F)


#*****************************************************************
# Dynamic time warping distance
#******************************************************************
# http://en.wikipedia.org/wiki/Dynamic_time_warping
# http://dtw.r-forge.r-project.org/
#******************************************************************
load.packages('dtw')

obj = bt.matching.find(Cl(data), normalize.fn = normalize.mean, dist.fn = 'dist.DTW', plot=T,, n.query=228,n.reference = 252*20)

matches = bt.matching.overlay(obj, plot.index=1:90, plot=T)

layout(1:2)
matches = bt.matching.overlay(obj, plot=T, layout=T)
bt.matching.overlay.table(obj, matches, plot=T, layout=T)

Source: Time Series Matching with Dynamic Time Warping

Interestingly enough, the runup starting in july 2011 is chosen as the closest match, and we all know how that ended. There are multiple other scenarios however.

The average returns of the top 9 matches seem to under perform the anytime/benchmark return (not shown).

More pattern matching posts to come in the future….

Now back to turkey day…..

Update: I ran the same code for the DJIA diamonds (DIA):


The same conclusions hold true, the runup starting in july 2011 is the closest match and the next week/month return is below average. In the future we will examine more pattern matching methods….

Trahan and Lazar: Buy Domestic Consumer and Industrial stocks

Interesting interview with Francois Trahan and Nancy Lazar. I’ve long been a fan of Trahan and his ‘Inflation is the new fed funds rate’ thesis, and now that he’s moved to a new firm to focus only on macro strategy I’m watching Cornerstone Macro LP very closely. Check out the interview below in which they discuss the outlook for the US:

Source: WealthTrack

Some of the takeaways:
• Macroeconomic influences have an outsized impact on equity market returns
• Dividends will contribute less to equity returns over the next few years. Markets driven mostly by PE expansion
• US has a low cost of energy because of natural gas
• Structural story of inflation being contained in US
• Emerging market bond sell-off and inflation problem: Indonesia yields from 5% to 9%, much worse than change in US yields
• Retail/Consumer stocks will have structural and cyclical outperformance vs materials/energy
• Buy US based industrial companies

I also recently came across this presentation by Trahan to the CFA society which has some great charts. In particular here are two slides that highlight the shift from a fed dominated market cycle to inflation dominated.

Source: Francois Trahan presentation to the CFA

I’ve also mentioned Trahan’s LEI framwork from his book in a previous post.

Beyond Crunching Numbers: How to Have Influence

I wanted to post this panel interview from the 2013 MIT Sloan Sports Analytics conference about how to influence people as a number crunching analyst. Its no secret that good stories influence much more than statistics. You’ll hear some good takeaways from analysts that have been very successful in their careers and have influenced others.

Gold: Dead cat bounce or double bottom?

Gold is at another interesting inflection point. After the break of support, gold crashed 15% in two days. It has since then staged a bounce and is now retesting support. Is it going to be a dead cat bounce and collapse further or a double bottom and rally?

Source: Stockcharts, PatternSite

Is the great trend over? I’m not sure, but if you’re an intevestor in gold I hope you’ve been double checking your thesis. A great place to start is the Golden Dilemma paper also here and here. In short, it examines the common reasons for holding gold, including:

“gold provides an inflation hedge”
“gold serves as a currency hedge”
“gold is an attractive alternative to assets with low real returns”
“gold a safe haven in times of stress”
“gold should be held because we are returning to a de facto world gold standard”
“gold is underowned”

Examine your own reasons carefully. Most people blindly buy into gold as a religion. I used to believe that gold was a hedge against instability but I’m not so sure anymore, as it trades more like a financial product, commoditized by wall street. Gold’s former role should have thrived in the current environment of intervention and positive feedback loops but it has since lost the qualities that have been described by others:

“The abandonment of the gold standard had broad cultural significance. It is no exaggeration to insist that going off the gold standard was the economic equivalent of the death of God. God functions in religious systems like gold functions in economic systems: God and gold are believed to be the firm foundations that provide a secure anchor for religious, moral, and economic values. When this foundation disappears, meaning and value become unmoored and once trustworthy symbols and signs float freely in turbulent currents that are constantly shifting.” ——Mark C. Taylor

The end of the gold standard (1973) unfettered the dollar from precious metal backing and laid the seeds for unconstrained credit growth. The economic consequences of the movement off of the gold standard have been incalculable, but the psychic effects have been no less profound. In a world in which financial promises are only as good as the counterparties that make them, gold is a promise kept. Gold is the anti-derivative, the anti-credit default swap, the anti-LBO. More important, it is the anti-dollar, the anti-fiat currency. And a fiat currency is the ultimate example of a promise, increasingly, a promise that can’t be kept. Gold is a tangible object in a world that came to overvalue intangible things. It is grounded in a world where few values are grounded. Most important, it is a physical good that is limited in supply. If the end of the world ever comes, gold will be your best friend. And it is indisputable that the end of the world is closer today than it was yesterday, and will be closer tomorrow than it is today

Source: Michael Lewitt

It seemed like the world was a perfect place for the former ‘foundation’ version of gold, with government intervention reaching new extremes in this Keynesian experiment. Positive feedback loops now taking place will have unintended consequences in the future. No one knows how this experiment will end. Gold seemed like the perfect place to hide….

Source: Ineichen Research and Management

As I said before, gold has traded more like a financial product lately than the foundation or hedge it was supposed to provide. Is the trend in financial assets to gold (Tangibles) finally reversing course?

Source: ShareLynx

No one can tell you for sure. As an investor, I don’t like gold under its support line around 1500. Under that line and its much harder to manage risk and know when you’re wrong. We shall see where gold heads in coming days.