Method: Daru::DateTimeIndex.date_range

Defined in:
lib/daru/date_time/index.rb

.date_range(opts = {}) ⇒ DateTimeIndex

Create a date range by specifying the start, end, periods and frequency of the data.

Notes

If you specify :start and :end options as strings, they can be complete or partial dates and daru will intelligently infer the date from the string directly. However, note that the date-like string must be in the format ‘YYYY-MM-DD HH:MM:SS`.

The string aliases supported by the :freq option are as follows:

  • ‘S’ - seconds

  • ‘M’ - minutes

  • ‘H’ - hours

  • ‘D’ - days

  • ‘W’ - Week (default) anchored on sunday

  • ‘W-SUN’ - Same as ‘W’

  • ‘W-MON’ - Week anchored on monday

  • ‘W-TUE’ - Week anchored on tuesday

  • ‘W-WED’ - Week anchored on wednesday

  • ‘W-THU’ - Week anchored on thursday

  • ‘W-FRI’ - Week anchored on friday

  • ‘W-SAT’ - Week anchored on saturday

  • ‘MONTH’ - Month

  • ‘YEAR’ - One year

  • ‘MB’ - month begin

  • ‘ME’ - month end

  • ‘YB’ - year begin

  • ‘YE’ - year end

Multiples of these can also be specified. For example ‘2S’ for 2 seconds or ‘2ME’ for two month end offsets.

Currently the precision of DateTimeIndex is upto seconds only, though this will improve in the future.

Examples:

Creating date ranges

Daru::DateTimeIndex.date_range(
  :start => DateTime.new(2014,5,1),
  :end   => DateTime.new(2014,5,2), :freq => '6H')
#=>#<DateTimeIndex:83600130 offset=H periods=5 data=[2014-05-01T00:00:00+00:00...2014-05-02T00:00:00+00:00]>

Daru::DateTimeIndex.date_range(
  :start => '2012-5-2', :periods => 50, :freq => 'ME')
#=> #<DateTimeIndex:83549940 offset=ME periods=50 data=[2012-05-31T00:00:00+00:00...2016-06-30T00:00:00+00:00]>

Parameters:

  • opts (Hash) (defaults to: {})

    Options hash to create the date range with

Options Hash (opts):

  • :start (String, DateTime)

    A DateTime object or date-like string that defines the start of the date range.

  • :end (String, DateTime)

    A DateTime object or date-like string that defines the end of the date range.

  • :freq (String, Daru::DateOffset, Daru::Offsets::*) — default: 'D'

    The interval between each date in the index. This can either be a string specifying the frequency (i.e. one of the frequency aliases) or an offset object.

  • :periods (Integer)

    The number of periods that should go into this index. Takes precedence over :end.

Returns:

  • (DateTimeIndex)

    DateTimeIndex object of the specified parameters.



336
337
338
339
340
341
342
343
344
# File 'lib/daru/date_time/index.rb', line 336

def self.date_range opts={}
  start  = Helper.coerce_date opts[:start]
  en     = Helper.coerce_date opts[:end]
  Helper.verify_start_and_end(start, en) unless en.nil?
  offset = Helper.offset_from_frequency opts[:freq]
  data   = Helper.generate_data start, en, offset, opts[:periods]

  DateTimeIndex.new(data, freq: offset)
end