<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/the-problem-with-depmix-for-online-regime-prediction/"></div></div><div><a data-url="https://www.r-bloggers.com/the-problem-with-depmix-for-online-regime-prediction/" data-counturl="https://www.r-bloggers.com/the-problem-with-depmix-for-online-regime-prediction/" data-count="horizontal" data-text="The Problem With Depmix For Online Regime Prediction" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://quantstrattrader.wordpress.com/2016/10/05/the-problem-with-depmix-with-online-prediction/"> R – QuantStrat TradeR</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This post will be about attempting to use the Depmix package for online state prediction. While the depmix package performs admirably when it comes to describing the states of the past, when used for one-step-ahead prediction, under the assumption that tomorrow’s state will be identical to today’s, the hidden markov model process found within the package does not perform to expectations.</p>
<p>So, to start off, this post was motivated by Michael Halls-Moore, who recently posted some R code about using the depmixS4 library to use hidden markov models. Generally, I am loath to create posts on topics I don’t feel I have an absolutely front-to-back understanding of, but I’m doing this in the hope of learning from others on how to appropriately do online state-space prediction, or “regime switching” detection, as it may be called in more financial parlance.</p>
<p><a target="_blank" href="https://www.quantstart.com/articles/hidden-markov-models-for-regime-detection-using-r">Here’s Dr. Halls-Moore’s post</a>.</p>
<p>While I’ve seen the usual theory of hidden markov models (that is, it can rain or it can be sunny, but you can only infer the weather judging by the clothes you see people wearing outside your window when you wake up), and have worked with toy examples in MOOCs (Udacity’s self-driving car course deals with them, if I recall correctly–or maybe it was the AI course), at the end of the day, theory is only as good as how well an implementation can work on real data.</p>
<p>For this experiment, I decided to take SPY data since inception, and do a full in-sample “backtest” on the data. That is, given that the HMM algorithm from depmix sees the whole history of returns, with this “god’s eye” view of the data, does the algorithm correctly classify the regimes, if the backtest results are any indication?</p>
<p>Here’s the code to do so, inspired by Dr. Halls-Moore’s.</p>
<pre>
require(depmixS4)
require(quantmod)
getSymbols('SPY', from = '1990-01-01', src='yahoo', adjust = TRUE)
spyRets &lt;- na.omit(Return.calculate(Ad(SPY)))

set.seed(123)

hmm &lt;- depmix(SPY.Adjusted ~ 1, family = gaussian(), nstates = 3, data=spyRets)
hmmfit &lt;- fit(hmm, verbose = FALSE)
post_probs &lt;- posterior(hmmfit)
post_probs &lt;- xts(post_probs, order.by=index(spyRets))
plot(post_probs$state)
summaryMat &lt;- data.frame(summary(hmmfit))
colnames(summaryMat) &lt;- c(&quot;Intercept&quot;, &quot;SD&quot;)
bullState &lt;- which(summaryMat$Intercept > 0)
bearState &lt;- which(summaryMat$Intercept &lt; 0)

hmmRets &lt;- spyRets * lag(post_probs$state == bullState) - spyRets * lag(post_probs$state == bearState)
charts.PerformanceSummary(hmmRets)
table.AnnualizedReturns(hmmRets)
</pre>
<p>Essentially, while I did select three states, I noted that anything with an intercept above zero is a bull state, and below zero is a bear state, so essentially, it reduces to two states.</p>
<p>With the result:</p>
<p><img src="https://i0.wp.com/cdn.discordapp.com/attachments/203286714720976896/233095201491648512/unknown.png?w=456&ssl=1" data-recalc-dims="1"></p>
<pre>
table.AnnualizedReturns(hmmRets)
                          SPY.Adjusted
Annualized Return               0.1355
Annualized Std Dev              0.1434
Annualized Sharpe (Rf=0%)       0.9448
</pre>
<p>So, not particularly terrible. The algorithm works, kind of, sort of, right?</p>
<p>Well, let’s try online prediction now.</p>
<pre>
require(DoMC)

dailyHMM &lt;- function(data, nPoints) {
  subRets &lt;- data[1:nPoints,]
  hmm &lt;- depmix(SPY.Adjusted ~ 1, family = gaussian(), nstates = 3, data = subRets)
  hmmfit &lt;- fit(hmm, verbose = FALSE)
  post_probs &lt;- posterior(hmmfit)
  summaryMat &lt;- data.frame(summary(hmmfit))
  colnames(summaryMat) &lt;- c(&quot;Intercept&quot;, &quot;SD&quot;)
  bullState &lt;- which(summaryMat$Intercept > 0)
  bearState &lt;- which(summaryMat$Intercept &lt; 0)
  if(last(post_probs$state) %in% bullState) {
    state &lt;- xts(1, order.by=last(index(subRets)))
  } else if (last(post_probs$state) %in% bearState) {
    state &lt;- xts(-1, order.by=last(index(subRets)))
  } else {
    state &lt;- xts(0, order.by=last(index(subRets)))
  }
  colnames(state) &lt;- &quot;State&quot;
  return(state)
}

# took 3 hours in parallel
t1 &lt;- Sys.time()
set.seed(123)
registerDoMC((detectCores() - 1))
states &lt;- foreach(i = 500:nrow(spyRets), .combine=rbind) %dopar% {
  dailyHMM(data = spyRets, nPoints = i)
}
t2 &lt;- Sys.time()
print(t2-t1)
</pre>
<p>So what I did here was I took an expanding window, starting from 500 days since SPY’s inception, and kept increasing it, by one day at a time. My prediction, was, trivially enough, the most recent day, using a 1 for a bull state, and a -1 for a bear state. I ran this process in parallel (on a linux cluster, because windows’s doParallel library seems to not even know that certain packages are loaded, and it’s more messy), and the first big issue is that this process took about three hours on seven cores for about 23 years of data. Not exactly encouraging, but computing time isn’t expensive these days. </p>
<p>So let’s see if this process actually works.</p>
<p>First, let’s test if the algorithm does what it’s actually supposed to do and use one day of look-ahead bias (that is, the algorithm tells us the state at the end of the day–how correct is it even for that day?).</p>
<pre>

onlineRets &lt;- spyRets * states 
charts.PerformanceSummary(onlineRets)
table.AnnualizedReturns(onlineRets)

</pre>
<p>With the result:</p>
<p><img src="https://i2.wp.com/cdn.discordapp.com/attachments/203286714720976896/233103311497199616/unknown.png?w=456&ssl=1" data-recalc-dims="1"></p>
<pre>
> table.AnnualizedReturns(onlineRets)
                          SPY.Adjusted
Annualized Return               0.2216
Annualized Std Dev              0.1934
Annualized Sharpe (Rf=0%)       1.1456
</pre>
<p>So, allegedly, the algorithm seems to do what it was designed to do, which is to classify a state for a given data set. Now, the most pertinent question: how well do these predictions do even one day ahead? You’d think that state space predictions would be parsimonious from day to day, given the long history, correct?</p>
<pre>

onlineRets &lt;- spyRets * lag(states)
charts.PerformanceSummary(onlineRets)
table.AnnualizedReturns(onlineRets)

</pre>
<p>With the result:</p>
<p><img src="https://i1.wp.com/cdn.discordapp.com/attachments/203286714720976896/233104133958139905/unknown.png?w=456&ssl=1" data-recalc-dims="1"></p>
<pre>
> table.AnnualizedReturns(onlineRets)
                          SPY.Adjusted
Annualized Return               0.0172
Annualized Std Dev              0.1939
Annualized Sharpe (Rf=0%)       0.0888
</pre>
<p>That is, without the lookahead bias, the state space prediction algorithm is atrocious. Why is that? </p>
<p>Well, here’s the plot of the states:</p>
<p><img src="https://i1.wp.com/cdn.discordapp.com/attachments/203286714720976896/233106642038816768/unknown.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>In short, the online hmm algorithm in the depmix package seems to change its mind very easily, with obvious (negative) implications for actual trading strategies.</p>
<p>So, that wraps it up for this post. Essentially, the main message here is this: there’s a vast difference between loading doing descriptive analysis (AKA “where have you been, why did things happen”) vs. predictive analysis (that is, “if I correctly predict the future, I get a positive payoff”). In my opinion, while descriptive statistics have their purpose in terms of explaining why a strategy may have performed how it did, ultimately, we’re always looking for better prediction tools. In this case, depmix, at least in this “out-of-the-box” demonstration does not seem to be the tool for that.</p>
<p>If anyone has had success with using depmix (or other regime-switching algorithm in R) for prediction, I would love to see work that details the procedure taken, as it’s an area I’m looking to expand my toolbox into, but don’t have any particular good leads. Essentially, I’d like to think of this post as me describing my own experiences with the package.</p>
<p>Thanks for reading.</p>
<p>NOTE: On Oct. 5th, I will be in New York City. On Oct. 6th, I will be presenting at The Trading Show on the Programming Wars panel. </p>
<p>NOTE: My current analytics contract is up for review at the end of the year, so I am officially looking for other offers as well. If you have a full-time role which may benefit from the skills you see on my blog, please get in touch with me. My linkedin profile can be found <a target="_blank" href="https://www.linkedin.com/in/ilyakipnis?trk=nav_responsive_tab_profile">here.</a></p>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/quantstrattrader.wordpress.com/487/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/quantstrattrader.wordpress.com/487/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/the-problem-with-depmix-for-online-regime-prediction/"></div></div><div><a data-url="https://www.r-bloggers.com/the-problem-with-depmix-for-online-regime-prediction/" data-counturl="https://www.r-bloggers.com/the-problem-with-depmix-for-online-regime-prediction/" data-count="vertical" data-text="The Problem With Depmix For Online Regime Prediction" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://quantstrattrader.wordpress.com/2016/10/05/the-problem-with-depmix-with-online-prediction/"> R – QuantStrat TradeR</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/VqqfeLfEMuM"></a></div>