Function Repository Resource:

TimeSeriesAlign

Source Notebook

Align multiple time series to begin at the same time

Contributed by: Bob Sandheinrich

ResourceFunction["TimeSeriesAlign"][{ts1,ts2,}]

shifts the time series tsi so the first time of each is aligned.

ResourceFunction["TimeSeriesAlign"][{ts1,ts2,},t0]

shifts the time series to all start at t0.

Details and Options

The start time t0 can be a DateObject or numeric value in seconds.
The default start time is Now.
The first time of each time series is given by tsi["FirstTime"].

Examples

Basic Examples (2) 

Shift two time series to start at time zero:

In[1]:=
ResourceFunction[
 "TimeSeriesAlign"][{TimeSeries[{{100, 1}, {101, 2}, {102, 3}}],
  TimeSeries[{{10, -1}, {11, -2}, {12, -3}}]}, 0]
Out[1]=

TimeSeriesAlign uses Now as the default start time. Shifting two time series to the current time, treats numeric values as seconds:

In[2]:=
ResourceFunction[
 "TimeSeriesAlign"][{TimeSeries[{{100000, 1}, {200000, 2}, {300000, 3}}],
  TimeSeries[{{-500000, -1}, {-400000, -2}, {-300000, -3}}]}]
Out[2]=

Plot it:

In[3]:=
DateListPlot[%]
Out[3]=

Scope (2) 

Align stock prices from different eras:

In[4]:=
ts1 = Entity["Financial", "NASDAQ:AAPL"][
EntityProperty[
  "Financial", "Price", {"Date" -> Interval[{
DateObject[{1990}], 
DateObject[{2010}]}]}]]
Out[4]=
In[5]:=
ts2 = Entity["Financial", "NYSE:IBM"][
EntityProperty[
  "Financial", "Price", {"Date" -> Interval[{
DateObject[{1975}], 
DateObject[{1995}]}]}]]
Out[5]=

Plot them with a shared time span:

In[6]:=
ListLinePlot@ResourceFunction["TimeSeriesAlign"][{ts1, ts2}]
Out[6]=

Applications (2) 

Align COVID-19 data for US counties so the date of the fifth death is shifted to today and chose only counties with at least ten data points:

In[7]:=
aligned = ResourceFunction["NYTimesCOVID19Data"]["USCountiesTimeSeries"][All, ResourceFunction["TimeSeriesSelect"][#Deaths, #2 > 5 &] &][
  Select[#["PathLength"] > 10 &]/*ResourceFunction["TimeSeriesAlign"]]
Out[7]=

Plot it:

In[8]:=
DateListLogPlot[aligned, PlotRange -> Full, FrameTicks -> {None, Automatic}]
Out[8]=

Version History

  • 1.0.0 – 02 April 2020

Related Resources

Author Notes

The handling of "Date" vs "Time" specs could be much improved.

License Information