I suspect many people working on timeseries data have already come across this issue, and pandas doesn't seem to provide a straightforward solution (yet!):
Suppose:
- You have a timeseries of daily data with Close prices, indexed by Date (day).
- Today is 19JUN. Last Close data value is 18JUN.
- You want to resample the daily data into OHLC bars, with some given frequency (let's say M or 2M) ending 18JUN.
So for M freq, last bar would be 19MAY-18JUN, previous one 19APR-18MAY, and so on...
ts.resample('M', how='ohlc')
will do the resampling, but 'M' is 'end_of_month' period so the result will give a full month for 2014-05 and a 2-week period for 2014-06, so your last bar won't be a 'monthly bar'. That's not what we want!
With 2M
frequency, given my sample timeseries, my test gives me last bar labelled as 2014-07-31 (and previous labelled as 2014-05-31), which is quite misleading since there's not data on JUL.... The supposed last 2-Month bar is again just covering the most recent 2 weeks.
The correct DatetimeIndex is easily created with:
pandas.date_range(end='2014-06-18', freq='2M', periods=300) + datetime.timedelta(days=18)
(Pandas documentation prefers to do the same thing via
pandas.date_range(end='2014-06-18', freq='2M', periods=300) + pandas.tseries.offsets.DateOffset(days=18)
but my tests shows that this method, though more 'pandaïc' is 2x slower!)
Either way we can't apply the right DatetimeIndex to ts.resample().
It seems that pandas dev team (Date ranges in Pandas) is aware of this issue, but in the meantime, how could you solve it to get OHLC with rolling frequency anchored on the last day in the timeseries?