Assume: I have a time series data, either a zoo or xts object.
Question: Is there any convenient function or method so that I can check whether the time series is monthly, quarterly or yearly?
You can compute the average difference between the timestamps, and check if it is closer to 1 (daily data), 7 (weekly), etc.
guess_period <- function(x) {
average_period <- as.double( mean(diff(index(x))), units="days" )
difference <- abs(log( average_period / c(
daily = 1,
business_days = 7/5,
weekly = 7,
monthly = 30,
quarterly = 365/4,
annual = 365
) ) )
names( which.min( difference ) )
}
# Examples
library(quantmod)
getSymbols("^GSPC")
guess_period( GSPC )
# [1] "business_days"
getSymbols('CPIAUCNS',src='FRED')
guess_period( CPIAUCNS )
# [1] "monthly"
The xts package has the function periodicity
for this purpose.
library(quantmod)
getSymbols("^GSPC")
periodicity(GSPC)
# Daily periodicity from 2007-01-03 to 2013-10-04
getSymbols("CPIAUCNS", src="FRED")
periodicity(CPIAUCNS)
# Monthly periodicity from 1913-01-01 to 2013-08-01
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With