Is there a way to approximate the periodicity of a time series in pandas? For R, the xts objects have a method called periodicity that serves exactly this purpose. Is there an implemented method to do so?
For instance, can we infer the frequency from time series that do not specify frequency?
import pandas.io.data as web
aapl = web.get_data_yahoo("AAPL")
<class 'pandas.tseries.index.DatetimeIndex'>
[2010-01-04 00:00:00, ..., 2013-12-19 00:00:00]
Length: 999, Freq: None, Timezone: None
The frequency of this series can reasonably be approximated to be daily.
Update:
I think it might be helpful to show the source code of R's implementation of the periodicity method.
function (x, ...)
{
if (timeBased(x) || !is.xts(x))
x <- try.xts(x, error = "'x' needs to be timeBased or xtsible")
p <- median(diff(.index(x)))
if (is.na(p))
stop("can not calculate periodicity of 1 observation")
units <- "days"
scale <- "yearly"
label <- "year"
if (p < 60) {
units <- "secs"
scale <- "seconds"
label <- "second"
}
else if (p < 3600) {
units <- "mins"
scale <- "minute"
label <- "minute"
p <- p/60L
}
else if (p < 86400) {
units <- "hours"
scale <- "hourly"
label <- "hour"
}
else if (p == 86400) {
scale <- "daily"
label <- "day"
}
else if (p <= 604800) {
scale <- "weekly"
label <- "week"
}
else if (p <= 2678400) {
scale <- "monthly"
label <- "month"
}
else if (p <= 7948800) {
scale <- "quarterly"
label <- "quarter"
}
structure(list(difftime = structure(p, units = units, class = "difftime"),
frequency = p, start = start(x), end = end(x), units = units,
scale = scale, label = label), class = "periodicity")
}
I think this line is the key, which I don't quite understand
p <- median(diff(.index(x)))