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.

Working with Tidy Financial Data in tidyr – Part III

Robot Wealth

Contributor:
Robot Wealth
Visit: Robot Wealth

See Part I and Part II to get started with the necessary data and R packages.

Pivoting from wide to long

For pivoting from wide to long, we use tidry::pivot_longer.

The most important arguments to the function are colsnames_to and values_to. You can probably guess at their relationship to the arguments to pivot_wider.

  • cols specifies the columns that we want to take from wide to long.
  • names_to specifies a name for the column in our long data frame that will hold the column names from the wide data frame.
  • values_to specifies a name for the column in our long data frame that will hold the values in the cells of the wide data frame.

In our example:

  • We want to take the columns holding the returns for each ticker from wide to long, so we want cols to take all the columns except date. We can do that by specifying cols = -date
  • We want the names of the cols to be held in a long variable called tickers, so we specify names_to = "ticker". Note that "ticker" here is a string variable.
  • We want to hold the values from our wide columns in a long column called "returns" so we specify values_to = "returns". Again note the string variable.

Here’s what that looks like:

dailyindex_df_wide %>%
pivot_longer(cols = -date, names_to = ‘ticker’, values_to= ‘returns’) %>%
kable() %>%
kable_styling(full_width = FALSE, position = ‘center’) %>%
scroll_box(width = ‘800px’, height = ‘300px’)

date EQ_US EQ_NONUS_DEV EQ_EMER TN_US TB_US BOND_EMER GOLD
2020-03-02 0.0460048 0.0111621 0.0114468 -0.0008475 -0.0073579 0.0051502 0.0179376
2020-03-03 -0.0280740 0.0097820 0.0106093 0.0093299 0.0154987 0.0093937 0.0311450
2020-03-04 0.0422302 0.0062777 0.0097196 -0.0016807 -0.0099536 0.0059222 -0.0008743
2020-03-05 -0.0336854 -0.0014521 0.0014743 0.0050505 0.0227882 -0.0067283 0.0151949
2020-03-06 -0.0170369 -0.0232132 -0.0262282 0.0041876 0.0498034 -0.0076207 0.0026644
2020-03-09 -0.0761665 0.0000000 0.0000000 0.0041701 0.0262172 0.0000000 0.0018757
2020-03-10 0.0494037 0.0000000 0.0000000 -0.0091362 -0.0486618 -0.0477816 -0.0091271
2020-03-11 -0.0487713 0.0000000 0.0000000 -0.0025147 -0.0108696 -0.0206093 -0.0107857
2020-03-12 -0.0949084 0.0000000 0.0000000 0.0008403 -0.0155139 0.0000000 -0.0317549
2020-03-13 0.0931900 0.0000000 0.0000000 -0.0058774 -0.0216678 -0.0439158 -0.0462765
2020-03-16 -0.1197921 0.0000000 0.0000000 0.0126689 0.0510067 -0.0325359 -0.0203396
2020-03-17 0.0597801 0.0000000 0.0000000 -0.0133445 -0.0587484 -0.0197824 0.0265681
2020-03-18 -0.0517360 0.0000000 0.0000000 -0.0067625 -0.0434193 -0.0544904 -0.0311081
2020-03-19 0.0047010 0.0000000 0.0000000 0.0017021 0.0007092 -0.0234792 0.0011498
2020-03-20 -0.0431907 0.0000000 0.0000000 0.0144435 0.0652020 0.0142077 0.0039756
2020-03-23 -0.0292942 -0.2532532 0.0000000 0.0083752 0.0419162 -0.0215517 0.0568462
2020-03-24 0.0939740 0.0000000 0.0000000 -0.0041528 -0.0051086 0.0121145 0.0575354
2020-03-25 0.0115569 0.0000000 0.0000000 0.0008340 -0.0064185 0.0315560 -0.0174002
2020-03-26 0.0624207 0.0000000 0.0000000 0.0016667 0.0064599 0.0295359 0.0159455
2020-03-27 -0.0336616 0.0000000 0.0000000 0.0049917 0.0237484 -0.0081967 -0.0037858
2020-03-30 0.0336403 0.0000000 0.0000000 -0.0008278 -0.0050157 -0.0144628 -0.0065711
2020-03-31 -0.0159221 0.0000000 0.0000000 -0.0016570 -0.0144928 0.0115304 -0.0283711
2020-04-01 -0.0441380 0.0000000 0.0000000 0.0008299 0.0147059 -0.0124352 -0.0032808
2020-04-02 0.0230223 0.0000000 0.0000000 0.0008292 0.0056711 0.0000000 0.0291310

And you can see that we’ve recovered our original long form dataframe.

An example

One example where you’d be forced to pivot you long returns data frame to wide would be to calculate a correlation matrix:

dailyindex_df %>%
pivot_wider(names_from = ticker, values_from = returns) %>%
select(-date) %>%
cor(use = “pairwise.complete.obs”, method=’pearson’) %>%
kable() %>%
kable_styling(position = ‘center’) %>%
scroll_box(width = ‘800px’, height = ‘300px’)

EQ_US EQ_NONUS_DEV EQ_EMER TN_US TB_US BOND_EMER GOLD
EQ_US 1.0000000 0.1045511 0.1219745 -0.5935488 -0.4827843 0.1064579 0.2741258
EQ_NONUS_DEV 0.1045511 1.0000000 0.1216288 -0.2460011 -0.2961201 0.1418452 -0.4301298
EQ_EMER 0.1219745 0.1216288 1.0000000 -0.0362846 -0.2751978 0.1345682 0.1158572
TN_US -0.5935488 -0.2460011 -0.0362846 1.0000000 0.9324163 0.3326693 0.1643955
TB_US -0.4827843 -0.2961201 -0.2751978 0.9324163 1.0000000 0.3107047 0.2451740
BOND_EMER 0.1064579 0.1418452 0.1345682 0.3326693 0.3107047 1.0000000 0.3305851
GOLD 0.2741258 -0.4301298 0.1158572 0.1643955 0.2451740 0.3305851 1.0000000

You can see that we’ve also used the select function from dplyr to drop the date column before passing the wide data frame of returns to the cor function for calculating the correlation matrix.

Plotting long format data

When you want to plot more than one variable on a single chart, long data is most definitely your friend:

dailyindex_df %>%
ggplot(aes(x = date, y = returns, colour = ticker)) +
geom_line()

Working with Tidy Financial Data in tidyr
Plotting each returns series in a grid is equally simple:

dailyindex_df %>%
ggplot(aes(x = date, y = returns)) +
geom_line() +
facet_wrap(~ticker)

Working with Tidy Financial Data in tidyr

Using wide-format data to make a similar plot would require repeated calls to geom_line for each variable, which is quite painstaking and brittle.

For example, if something changes upstream, such as the addition of a new ticker to the data set, your code will also need to change in order to plot it. That’s not the case if we use long data with a column holding the ticker variable.

Visit Robot Wealth website to read the full article and watch the instructional video: https://robotwealth.com/working-with-tidy-financial-data-in-tidyr/

Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight 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 permission from Robot Wealth. The views expressed in this material are solely those of the author and/or Robot Wealth and IBKR 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 sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. 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.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

trading top