Asset Classes

Free investment financial education

Language

Multilingual content from IBKR

Close Navigation
Learn more about IBKR accounts
How to Fill Gaps in Large Stock Data Universes Using tidyr and dplyr – Part III

How to Fill Gaps in Large Stock Data Universes Using tidyr and dplyr – Part III

Posted October 7, 2021 at 10:53 am
Robot James
Robot Wealth

Learn how to use tidyverse with these practical examples in Part I and Part II.

What if we have more than one variable in our orignal data?

One of the benefits of working with longer “tidy” data is that we can have multiple variables per date/stock observation.

testwider <- testdata %>%
  mutate(volume = 100:106,
         otherfeature = 200:206)
testwider
## # A tibble: 7 x 5
##    date ticker returns volume otherfeature
##   <dbl> <chr>    <dbl>  <int>        <int>
## 1     1 AMZN      0.01    100          200
## 2     1 FB        0.02    101          201
## 3     2 AMZN      0.03    102          202
## 4     2 FB        0.04    103          203
## 5     2 TSLA      0.05    104          204
## 6     3 AMZN      0.06    105          205
## 7     3 TSLA      0.07    106          206

Again, we’re missing data for TSLA on date 1 and FB on date 3, but now we’re also missing volume and otherfeature in addition to returns.

To use complete, nothing changes from earlier:

testwider %>%
  complete(date, ticker)
## # A tibble: 9 x 5
##    date ticker returns volume otherfeature
##   <dbl> <chr>    <dbl>  <int>        <int>
## 1     1 AMZN      0.01    100          200
## 2     1 FB        0.02    101          201
## 3     1 TSLA     NA        NA           NA
## 4     2 AMZN      0.03    102          202
## 5     2 FB        0.04    103          203
## 6     2 TSLA      0.05    104          204
## 7     3 AMZN      0.06    105          205
## 8     3 FB       NA        NA           NA
## 9     3 TSLA      0.07    106          206

However if we want to pivot back and forth, we do the following:

  • use pivot_wide to reshape the data to row per date, with a column for each stock
  • use pivot_long to reshape it back to its longer format
  • use left_join to recover the rest of the variables from the original data.
testwider %>%
  pivot_wider(id_cols = date, names_from = ticker, values_from = returns) %>%
  pivot_longer(-date, names_to = 'ticker', values_to =  'returns') %>%
  left_join(testwider, by = c('date', 'ticker', 'returns'))
## # A tibble: 9 x 5
##    date ticker returns volume otherfeature
##   <dbl> <chr>    <dbl>  <int>        <int>
## 1     1 AMZN      0.01    100          200
## 2     1 FB        0.02    101          201
## 3     1 TSLA     NA        NA           NA
## 4     2 AMZN      0.03    102          202
## 5     2 FB        0.04    103          203
## 6     2 TSLA      0.05    104          204
## 7     3 AMZN      0.06    105          205
## 8     3 FB       NA        NA           NA
## 9     3 TSLA      0.07    106          206

Conclusions

  • Missing values in financial data threaten the validity of quant analysis due to inadvertent misalignment
  • Wide data tends to highlight such missing data
  • Long data tends to hide it
  • tidyr::complete is a succinct and efficient way to ensure that missing observations are accounted for with NA
  • Like most tasks in R, there is more than one way to go about it. But complete should be your go-to function.

Want all the code?

All the code in this post is available in our github repo where you can find lots of other recipes and tools to make your life as a quant researcher easier.

See the full article on Robot Wealth website: https://robotwealth.com/how-to-fill-gaps-in-large-stock-data-universes-using-tidyr-and-dplyr/.

Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from Robot Wealth and is being posted with its permission. The views expressed in this material are solely those of the author and/or Robot Wealth and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

Disclosure: Displaying Symbols on Video

Any stock, options or futures symbols displayed are for illustrative purposes only and are not intended to portray recommendations.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.