<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/constant-expiry-vix-futures-using-public-data/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://quantstrattrader.wordpress.com/2017/05/18/constant-expiry-vix-futures-using-public-data/"> 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 creating constant expiry (E.G. a rolling 30-day contract) using VIX settlement data from the CBOE and the spot VIX calculation (from Yahoo finance, or wherever else). Although these may be able to be traded under certain circumstances, this is not always the case (where the desired expiry is shorter than the front month’s time to expiry).</p>
<p>The last time I visited this topic, I created a term structure using publicly available data from the CBOE, along with an external expiry calendar.</p>
<p>The logical next step, of course, is to create constant-expiry contracts, which may or may not be tradable (if your contract expiry is less than 30 days, know that the front month has days in which the time to expiry is more than 30 days).</p>
<p>So here’s where we left off: <a rel="nofollow" href="https://quantstrattrader.wordpress.com/2017/04/27/creating-a-vix-futures-term-structure-in-r-from-official-cboe-settlement-data/" target="_blank">a way to create a continuous term structure using CBOE settlement VIX data.</a></p>
<p>So from here, before anything, we need to get VIX data. And while the getSymbols command used to be easier to use, because Yahoo broke its API (what else do you expect from an otherwise-irrelevant, washed-up web 1.0 dinosaur?), it’s not possible to get free Yahoo data at this point in time (in the event that Josh Ulrich doesn’t fix this issue in the near future, I’m open to suggestions for other free sources of data which provide data of reputable quality), so we need to get VIX data from elsewhere (particularly, the CBOE itself, which is a one-stop shop for all VIX-related data…and most likely some other interesting futures as well.)</p>
<p>So here’s how to get VIX data from the CBOE (thanks, all you awesome CBOE people! And a shoutout to all my readers from the CBOE, I’m sure some of you are from there).</p>
<pre>
VIX &lt;- fread(&quot;http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vixcurrent.csv&quot;, skip = 1)
VIXdates &lt;- VIX$Date
VIX$Date &lt;- NULL; VIX &lt;- xts(VIX, order.by=as.Date(VIXdates, format = '%m/%d/%Y'))
spotVix &lt;- Cl(VIX)
</pre>
<p>Next, there’s a need for some utility functions to help out with identifying which futures contracts to use for constructing synthetics.</p>
<pre>
# find column with greatest days to expiry less than or equal to desired days to expiry
shortDurMinMax &lt;- function(row, daysToExpiry) {
  return(max(which(row &lt;= daysToExpiry)))
}

# find column with least days to expiry greater desired days to expiry
longDurMinMax &lt;- function(row, daysToExpiry) {
  return(min(which(row > daysToExpiry)))
}

# gets the difference between the two latest contracts (either expiry days or price)
getLastDiff &lt;- function(row) {
  indices &lt;- rev(which(!is.na(row)))
  out &lt;- row[indices[1]] - row[indices[2]]
  return(out)
}

# gets the rightmost non-NA value of a row
getLastValue &lt;- function(row) {
  indices &lt;- rev(which(!is.na(row)))
  out &lt;- row[indices[1]]
  return(out)
}
</pre>
<p>The first two functions are to determine short-duration and long-duration contracts. Simply, provided a row of data and the desired constant time to expiry, the first function finds the contract with a time closest to expiry less than or equal to the desired amount, while the second function does the inverse.</p>
<p>The next two functions are utilized in the scenario of a function whose time to expiry is greater than the expiry of the longest trading contract. Such a synthetic would obviously not be able to be traded, but can be created for the purposes of using as an indicator. The third function gets the last two non-NA values in a row (I.E. the two last prices, the two last times to expiry), and the fourth one simply gets the rightmost non-NA value in a row.</p>
<p>The algorithm to create a synthetic constant-expiry contract/indicator is divided into three scenarios:</p>
<p>One, in which the desired time to expiry of the contract is shorter than the front month, such as a constant 30-day expiry contract, when the front month has more than 30 days to maturity (such as on Nov 17, 2016), at which point, the weight will be the desired time to expiry over the remaining time to expiry in the front month, and the remainder in spot VIX (another asset that cannot be traded, at least conventionally).</p>
<p>The second scenario is one in which the desired time to expiry is longer than the last traded contract. For instance, if the desire was to create a contract<br>
with a year to expiry when the furthest out is eight months, there obviously won’t be data for such a contract. In such a case, the algorithm is to compute the linear slope between the last two available contracts, and add the extrapolated product of the slope multiplied by the time remaining between the desired and the last contract to the price of the last contract.</p>
<p>Lastly, the third scenario (and the most common one under most use cases) is that of the synthetic for which there is both a trading contract that has less time to expiry than the desired constant rate, and one with more time to expiry. In this instance, a matter of linear algebra (included in the comments) denotes the weight of the short expiry contract, which is (desired – expiry_long)/(expiry_short – expiry_long).</p>
<p>The algorithm iterates through all three scenarios, and due to the mechanics of xts automatically sorting by timestamp, one obtains an xts object in order of dates of a synthetic, constant expiry futures contract.</p>
<p>Here is the code for the function.</p>
<pre>

constantExpiry &lt;- function(spotVix, termStructure, expiryStructure, daysToExpiry) {
  
  # Compute synthetics that are too long (more time to expiry than furthest contract)
  
  # can be Inf if no column contains values greater than daysToExpiry (I.E. expiry is 3000 days)
  suppressWarnings(longCol &lt;- xts(apply(expiryStructure, 1, longDurMinMax, daysToExpiry), order.by=index(termStructure)))
  longCol[longCol == Inf] &lt;- 10
  
  # xts for too long to expiry -- need a NULL for rbinding if empty
  tooLong &lt;- NULL
  
  # Extend the last term structure slope an arbitrarily long amount of time for those with too long expiry
  tooLongIdx &lt;- index(longCol[longCol==10])
  if(length(tooLongIdx) > 0) {
    tooLongTermStructure &lt;- termStructure[tooLongIdx]
    tooLongExpiryStructure &lt;- expiryStructure[tooLongIdx]
    
    # difference in price/expiry for longest two contracts, use it to compute a slope
    priceDiff &lt;- xts(apply(tooLongTermStructure, 1, getLastDiff), order.by = tooLongIdx)
    expiryDiff &lt;- xts(apply(tooLongExpiryStructure, 1, getLastDiff), order.by = tooLongIdx)
    slope &lt;- priceDiff/expiryDiff
    
    # get longest contract price and compute additional days to expiry from its time to expiry 
    # I.E. if daysToExpiry is 180 and longest is 120, additionalDaysToExpiry is 60
    maxDaysToExpiry &lt;- xts(apply(tooLongExpiryStructure, 1, max, na.rm = TRUE), order.by = tooLongIdx)
    longestContractPrice &lt;- xts(apply(tooLongTermStructure, 1, getLastValue), order.by = tooLongIdx)
    additionalDaysToExpiry &lt;- daysToExpiry - maxDaysToExpiry
    
    # add slope multiplied by additional days to expiry to longest contract price
    tooLong &lt;- longestContractPrice + additionalDaysToExpiry * slope
  }
  
  # compute synthetics that are too short (less time to expiry than shortest contract)
  
  # can be -Inf if no column contains values less than daysToExpiry (I.E. expiry is 5 days)
  suppressWarnings(shortCol &lt;- xts(apply(expiryStructure, 1, shortDurMinMax, daysToExpiry), order.by=index(termStructure)))
  shortCol[shortCol == -Inf] &lt;- 0
  
  # xts for too short to expiry -- need a NULL for rbinding if empty
  tooShort &lt;- NULL
  
  tooShortIdx &lt;- index(shortCol[shortCol==0])
  
  if(length(tooShortIdx) > 0) {
    tooShort &lt;- termStructure[,1] * daysToExpiry/expiryStructure[,1] + spotVix * (1 - daysToExpiry/expiryStructure[,1])
    tooShort &lt;- tooShort[tooShortIdx]
  }
  
  
  # compute everything in between (when time to expiry is between longest and shortest)
  
  # get unique permutations for contracts that term structure can create
  colPermutes &lt;- cbind(shortCol, longCol)
  colnames(colPermutes) &lt;- c(&quot;short&quot;, &quot;long&quot;)
  colPermutes &lt;- colPermutes[colPermutes$short > 0,]
  colPermutes &lt;- colPermutes[colPermutes$long &lt; 10,]
  
  regularSynthetics &lt;- NULL
  
  # if we can construct synthetics from regular futures -- someone might enter an extremely long expiry
  # so this may not always be the case
  
  if(nrow(colPermutes) > 0) {
    
    # pasting long and short expiries into a single string for easier subsetting
    shortLongPaste &lt;- paste(colPermutes$short, colPermutes$long, sep=&quot;_&quot;)
    uniqueShortLongPaste &lt;- unique(shortLongPaste)
    
    regularSynthetics &lt;- list()
    for(i in 1:length(uniqueShortLongPaste)) {
      # get unique permutation of short-expiry and long-expiry contracts
      permuteSlice &lt;- colPermutes[which(shortLongPaste==uniqueShortLongPaste[i]),]
      expirySlice &lt;- expiryStructure[index(permuteSlice)]
      termStructureSlice &lt;- termStructure[index(permuteSlice)]
      
      # what are the parameters?
      shortCol &lt;- unique(permuteSlice$short); longCol &lt;- unique(permuteSlice$long)
      
      # computations -- some linear algebra
      
      # S/L are weights, ex_S/ex_L are time to expiry
      # D is desired constant time to expiry
      
      # S + L = 1
      # L = 1 - S
      # S + (1-S) = 1
      # 
      # ex_S * S + ex_L * (1-S) = D
      # ex_S * S + ex_L - ex_L * S = D
      # ex_S * S - ex_L * S = D - ex_L
      # S(ex_S - ex_L) = D - ex_L
      # S = (D - ex_L)/(ex_S - ex_L)
      
      weightShort &lt;- (daysToExpiry - expirySlice[, longCol])/(expirySlice[, shortCol] - expirySlice[, longCol])
      weightLong &lt;- 1 - weightShort
      syntheticValue &lt;- termStructureSlice[, shortCol] * weightShort + termStructureSlice[, longCol] * weightLong
      
      regularSynthetics[[i]] &lt;- syntheticValue
    }
    
    regularSynthetics &lt;- do.call(rbind, regularSynthetics)
  }
  
  out &lt;- rbind(tooShort, regularSynthetics, tooLong)
  colnames(out) &lt;- paste0(&quot;Constant_&quot;, daysToExpiry)
  return(out)
}
</pre>
<p>And here’s how to use it:</p>
<pre>
constant30 &lt;- constantExpiry(spotVix = vixSpot, termStructure = termStructure, expiryStructure = expiryStructure, daysToExpiry = 30)
constant180 &lt;- constantExpiry(spotVix = vixSpot, termStructure = termStructure, expiryStructure = expiryStructure, daysToExpiry = 180)

constantTermStructure &lt;- cbind(constant30, constant180)

chart.TimeSeries(constantTermStructure, legend.loc = 'topright', main = &quot;Constant Term Structure&quot;)
</pre>
<p>With the result:<br>
<img data-orig-file="https://quantstrattrader.files.wordpress.com/2017/05/capture.png?w=456" data-orig-size="526,344" data-medium-file="https://quantstrattrader.files.wordpress.com/2017/05/capture.png?w=456?w=300" data-attachment-id="822" data-image-meta="{" data-image-description="" src="https://quantstrattrader.files.wordpress.com/2017/05/capture.png?w=456" data-permalink="https://quantstrattrader.wordpress.com/2017/05/18/constant-expiry-vix-futures-using-public-data/capture/#main" data-large-file="https://quantstrattrader.files.wordpress.com/2017/05/capture.png?w=456?w=526" alt="Capture" data-image-title="Capture" sizes="(max-width: 526px) 100vw, 526px" data-comments-opened="1" class="wp-image-822" data-recalc-dims="1"></p>
<p>Which means that between the CBOE data itself, and this function that creates constant expiry futures from CBOE spot and futures prices, one can obtain any futures contract, whether real or synthetic, to use as an indicator for volatility trading strategies. This allows for exploration of a wide variety of volatility trading strategies.</p>
<p>Thanks for reading.</p>
<p>NOTE: I am always interested in networking and hearing about full-time opportunities related to my skill set. My linkedin can be found <a rel="nofollow" href="https://www.linkedin.com/in/ilyakipnis/" target="_blank">here.</a> </p>
<p>Furthermore, if you are a volatility ETF/futures trading professional, I am interested in possible project-based collaboration. If you are interested, please contact me. </p>
<p> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/quantstrattrader.wordpress.com/760/" target="_blank"><img border="0" alt="" src="http://feeds.wordpress.com/1.0/comments/quantstrattrader.wordpress.com/760/"></a> <img border="0" alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" data-recalc-dims="1"></p>
<p>
<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/2017/05/18/constant-expiry-vix-futures-using-public-data/"> 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 rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/xkDcBn7zxNU" height="1"></a></div>