Aggregating to lower frequency

Importing and Managing Financial Data in R

Joshua Ulrich

Quantitative Analyst & quantmod Co-Author and Maintainer

Low frequency data

  • Timestamps have too much resolution
  • Represent the first quarter of 2017
    • "2017-01-01"(first)
    • "2017-03-31" (last)
    • "2017-02-01" (middle)
Importing and Managing Financial Data in R

Example

  • Compare the daily 10-year Treasury constant maturity rate with USA Gross Domestic Product (quarterly)
  • FRED symbols:
    • DGS10
    • GDP
Importing and Managing Financial Data in R

Merge aggregated data with low-frequency data

# Aggregate to quarterly
QGS10 <- apply.quarterly(DGS10, median, na.rm = TRUE)

# Merge quarterly aggregate with quarterly GDP QGS10_GDP <- merge(QGS10, GDP) QGS10_GDP
           DGS10     GDP
2015-01-01    NA 17783.6
2015-03-31  1.97      NA
2015-04-01    NA 17998.3
2015-06-30  2.19      NA
2015-07-01    NA 18141.9
2015-09-30  2.20      NA
2015-10-01    NA 18222.8
2015-12-31  2.23      NA
Importing and Managing Financial Data in R

Low frequency date-time classes

  • yearmon() for monthly data
  • yearqtr() for quarterly data
as.Date("2017-01-01")
"2017-01-01"
as.yearmon("2017-01-01")
"Jan 2017"
as.yearqtr("2017-01-01")
"2017 Q1"
Importing and Managing Financial Data in R

Convert index to lowest frequency

# Convert both indexes to yearqtr
index(QGS10) <- as.yearqtr(index(QGS10))
index(GDP) <- as.yearqtr(index(GDP))
# Merging 'just works'
merge(QGS10, GDP)
        DGS10     GDP
2015 Q1  1.97 17783.6
2015 Q2  2.19 17998.3
2015 Q3  2.20 18141.9
2015 Q4  2.23 18222.8
Importing and Managing Financial Data in R

Align with beginning-of-period timestamp

# Last observation carried backward
QGS10_GDP_locb <- na.locf(QGS10_GDP, fromLast = TRUE)
# Subset by beginning-of-period index
QGS10_GDP_first_period <- QGS10_GDP_locb[index(GDP)]
QGS10_GDP_first_period
          DGS10     GDP
2015-01-01  1.97 17783.6
2015-04-01  2.19 17998.3
2015-07-01  2.20 18141.9
2015-10-01  2.23 18222.8
Importing and Managing Financial Data in R

Let's practice!

Importing and Managing Financial Data in R

Preparing Video For Download...