Project

fat_period

0.0
A long-lived project that still receives updates
Implements a Period class as a Range of Dates.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

>= 7.0
>= 0.3.0
 Project Readme
  • Version
  • Introduction
  • Installation
    • Installing the gem
  • Usage
    • Constant Period::FOREVER
    • Construction of Periods
      • Period.new
      • Period.parse
      • Period.parse_phrase
      • Period.ensure
    • Conversion
      • #to_range
      • #to_s
      • #tex_quote
    • Comparison
    • Enumeration
      • #each
      • #size
    • Chunking
      • Period.<chunk>_containing(date)
      • #chunk_sym and #chunk_name
      • #chunks(size: :month, partial_first: true, partial_last: true, round_up_last: false)
    • Set Operations
      • #subset_of?(other)
      • #proper_subset_of?(other)
      • #superset_of(other)
      • #proper_superset_of(other)
      • #intersection(other)
      • #union(other)
      • #difference(other)
    • Coverage
      • #contains?(date)
      • Period.overlaps_among?(periods)
      • #overlaps_among?
      • #spanned_by(periods)
      • #gaps
    • Interest Day-count fraction (#year_fraction)
      • Choosing a convention
      • Actual-day conventions and boundaries
      • Sources
  • Development
  • Contributing

CI

Version

  "Current version is: #{FatPeriod::VERSION}"
Current version is: 3.1.0

Introduction

FatPeriod provides a Ruby Period class for dealing with time periods of days, that is ranges whose endpoints are of class Date. It's target is financial applications, but it serves well for any application where periods of time are useful. It builds on the fat_date gem, which provides enhancements to the Date class, especially its class method Date.spec for interpreting a rich set of "specs" as the beginning or end of a variety of calendar-related periods.

In addition, set operations are provided for Period, as well as methods for breaking a larger periods into an array of smaller periods of various 'chunk' sizes that correspond to calendar-related periods such as days, weeks, months, and so forth.

Installation

Installing the gem

Add this line to your application's Gemfile:

  gem 'fat_period'
true

And then execute:

  $ bundle

Or install it yourself as:

  $ gem install fat_period

Usage

Constant Period::FOREVER

The Period class depends on the extensions to Date made by the fat_core gem, which you can read about here. It defines a constant, Period::FOREVER, which is defined as extending from Date::BOT to Date::EOT, which are defined in fat_date as 1900-01-01 and 3000-12-31, respectively and define the beginning of time and end of time for practical commercial purposes. The constant is not frozen, so you can re-define it to your liking.

Construction of Periods

Period.new

A Period is constructed with two arguments for the begin and end date. The begin date must be on or before the end date. Each argument can be (1) a Date, (2) a string parseable as a Date by the Date.parse method, or (3) an object that responds to #to_s and can be parsed as a Date by Date.parse:

  p1 = Period.new(Date.today, Date.today + 30)
  p2 = Period.new('Nov 22, 1963', Date.today)
  p3 = Period.new('1961-01-21', '1963-11-22')
  [[p1.to_s], [p2.to_s], [p3.to_s]]
| 2026-11-05 to 2026-12-05 |
| 1963-11-22 to 2026-11-05 |
| 1961-01-21 to 1963-11-22 |
  ["Camelot lasted #{p3.length} days"]
| Camelot lasted 1036 days |

Period.parse

A more convenient way to construct a period is provided by Period.parse. It takes two strings as its arguments, a mandatory "from-spec" and an optional "to-spec":

A "spec" is a string designating some period of time. There are many ways of specifying a period, which are detailed below.

  1. With Only a From-Spec

    If only a from-spec is given, it defines both the beginning and end of the overall period:

      tab = []
      tab << ['From Spec', 'Result']
      tab << nil
      froms = ['2020', '2020-2Q', '2020-W15', '2020-09', '2020-09-A', '2020-09-iii']
      froms.each do |f|
        tab << [f, Period.parse(f).inspect]
      end
      tab
    | From Spec   | Result                         |
    |-------------+--------------------------------|
    | 2020        | Period(2020-01-01..2020-12-31) |
    | 2020-2Q     | Period(2020-04-01..2020-06-30) |
    | 2020-W15    | Period(2020-04-06..2020-04-12) |
    | 2020-09     | Period(2020-09-01..2020-09-30) |
    | 2020-09-A   | Period(2020-09-01..2020-09-15) |
    | 2020-09-iii | Period(2020-09-14..2020-09-20) |
    
    | From Spec   | Result                         |
    |-------------+--------------------------------|
    | 2020        | Period(2020-01-01..2020-12-31) |
    | 2020-2Q     | Period(2020-04-01..2020-06-30) |
    | 2020-W15    | Period(2020-04-06..2020-04-12) |
    | 2020-09     | Period(2020-09-01..2020-09-30) |
    | 2020-09-A   | Period(2020-09-01..2020-09-15) |
    | 2020-09-iii | Period(2020-09-14..2020-09-20) |
    
  2. With Both a From-Spec and To-Spec

    But, if a to-spec is also given, the from-spec defines the beginning of the period and the to-spec defines the end of the period. In particular, the beginning of the period is the first day of the from-spec and the end of the period is the last day of the to-spec:

      tab = []
      tab << ['From Spec', 'To Spec', 'Result']
      tab << nil
      from_tos = [['2020', '2020-2Q'], ['2020-2Q', '2020-W15'], ['2020-W15', '2020-09'], ['2020-09', '2020-09-A'], ['2020-09-A', '2020-09-iii']]
      from_tos.each do |f, t|
        tab << [f, t, Period.parse(f, t).inspect]
      end
      tab
    | From Spec | To Spec     | Result                         |
    |-----------+-------------+--------------------------------|
    | 2020      | 2020-2Q     | Period(2020-01-01..2020-06-30) |
    | 2020-2Q   | 2020-W15    | Period(2020-04-01..2020-04-12) |
    | 2020-W15  | 2020-09     | Period(2020-04-06..2020-09-30) |
    | 2020-09   | 2020-09-A   | Period(2020-09-01..2020-09-15) |
    | 2020-09-A | 2020-09-iii | Period(2020-09-01..2020-09-20) |
    
    | From Spec | To Spec     | Result                         |
    |-----------+-------------+--------------------------------|
    | 2020      | 2020-2Q     | Period(2020-01-01..2020-06-30) |
    | 2020-2Q   | 2020-W15    | Period(2020-04-01..2020-04-12) |
    | 2020-W15  | 2020-09     | Period(2020-04-06..2020-09-30) |
    | 2020-09   | 2020-09-A   | Period(2020-09-01..2020-09-15) |
    | 2020-09-A | 2020-09-iii | Period(2020-09-01..2020-09-20) |
    
  3. Using Skip Modifiers

    One new feature of FatDate is the ability to add a "skip modifier" to the end of a date spec to skip forward or backward to the first day-of-week either on or before/after the date given by the spec. For example, the following demonstrates that one can set the 'to' spec to the last Wednesday of 2025 or the last Wednesday before the end of 2025. Using '>' or '>=' specified skipping forward instead.

      tab = []
      tab << ['From Spec', 'To Spec', 'Result', 'Description']
      tab << nil
      from_to_descs = [['2025-2Q', '2025<=Wed', 'From 2q to last Wednesday of 2025'],
                       ['2025-2Q', '2025<Wed', 'From 2q to last Wednesday /before/ the end of 2025'],
                       ['2012-11', '2012-11<=Thur', 'November 2012 through last Thursday'],
                       ['2012-11', '2012-11-4Thur', 'And through Thanksgiving (not always the /last/ Thursday!)']
                      ]
      from_to_descs.each do |f, t, d|
        tab << [f, t, Period.parse(f, t).inspect, d]
      end
      tab
    | From Spec | To Spec       | Result                         | Description                                                |
    |-----------+---------------+--------------------------------+------------------------------------------------------------|
    | 2025-2Q   | 2025<=Wed     | Period(2025-04-01..2025-12-31) | From 2q to last Wednesday of 2025                          |
    | 2025-2Q   | 2025<Wed      | Period(2025-04-01..2025-12-31) | From 2q to last Wednesday /before/ the end of 2025         |
    | 2012-11   | 2012-11<=Thur | Period(2012-11-01..2012-11-29) | November 2012 through last Thursday                        |
    | 2012-11   | 2012-11-4Thur | Period(2012-11-01..2012-11-22) | And through Thanksgiving (not always the /last/ Thursday!) |
    
    | From Spec | To Spec       | Result                         | Description                                                |
    |-----------+---------------+--------------------------------+------------------------------------------------------------|
    | 2025-2Q   | 2025<=Wed     | Period(2025-04-01..2025-12-31) | From 2q to last Wednesday of 2025                          |
    | 2025-2Q   | 2025<Wed      | Period(2025-04-01..2025-12-31) | From 2q to last Wednesday /before/ the end of 2025         |
    | 2012-11   | 2012-11<=Thur | Period(2012-11-01..2012-11-29) | November 2012 through last Thursday                        |
    | 2012-11   | 2012-11-4Thur | Period(2012-11-01..2012-11-22) | And through Thanksgiving (not always the /last/ Thursday!) |
    

Period.parse_phrase

For example:

The Period.parse_phrase method will take a string having a 'from', 'to', and 'per' clause and return an Array of Periods encompassing the same period as Period.parse, but optionally broken into sub-periods each having the length specified by the 'per' clause. Period.parse_phrase always returns an Array of Periods even if there is no 'per' clause and the Array has only one member. If there is no 'to' clause, the returned period is from the start of the 'from' period to its end. If there is neither a 'from' or a 'to' clause, it tries to interpret the beginning of the phrase as a valid spec and uses it as a 'from' clause.

  tab = []
  tab << ['k', 'Sub Period']
  tab << nil
  pds = Period.parse_phrase('from 2025 to 2025-3Q per month')
  pds.each_with_index do |pd, k|
    tab << [k, pd.inspect]
  end
  tab
| k | Sub Period                     |
|---+--------------------------------|
| 0 | Period(2025-01-01..2025-01-31) |
| 1 | Period(2025-02-01..2025-02-28) |
| 2 | Period(2025-03-01..2025-03-31) |
| 3 | Period(2025-04-01..2025-04-30) |
| 4 | Period(2025-05-01..2025-05-31) |
| 5 | Period(2025-06-01..2025-06-30) |
| 6 | Period(2025-07-01..2025-07-31) |
| 7 | Period(2025-08-01..2025-08-31) |
| 8 | Period(2025-09-01..2025-09-30) |

The period named in the 'per' clause is called a 'chunk' and there are several valid chunk names in FatPeriod:

Chunk Name
year
half
quarter
bimonth
month
semimonth
biweek
week
day

Here is the same period broken into weeks. Notice that the first and last "weeks" are not whole weeks because parts of them fall outside the boundaries of the overall period.

  tab = []
  tab << ['k', 'Sub Period']
  tab << nil
  pds = Period.parse_phrase('from 2025 to 2025-3Q per week')
  pds.each_with_index do |pd, k|
    tab << [k, pd.inspect]
  end
  tab
|  k | Sub Period                     |
|----+--------------------------------|
|  0 | Period(2025-01-01..2025-01-05) |
|  1 | Period(2025-01-06..2025-01-12) |
|  2 | Period(2025-01-13..2025-01-19) |
|  3 | Period(2025-01-20..2025-01-26) |
|  4 | Period(2025-01-27..2025-02-02) |
|  5 | Period(2025-02-03..2025-02-09) |
|  6 | Period(2025-02-10..2025-02-16) |
|  7 | Period(2025-02-17..2025-02-23) |
|  8 | Period(2025-02-24..2025-03-02) |
|  9 | Period(2025-03-03..2025-03-09) |
| 10 | Period(2025-03-10..2025-03-16) |
| 11 | Period(2025-03-17..2025-03-23) |
| 12 | Period(2025-03-24..2025-03-30) |
| 13 | Period(2025-03-31..2025-04-06) |
| 14 | Period(2025-04-07..2025-04-13) |
| 15 | Period(2025-04-14..2025-04-20) |
| 16 | Period(2025-04-21..2025-04-27) |
| 17 | Period(2025-04-28..2025-05-04) |
| 18 | Period(2025-05-05..2025-05-11) |
| 19 | Period(2025-05-12..2025-05-18) |
| 20 | Period(2025-05-19..2025-05-25) |
| 21 | Period(2025-05-26..2025-06-01) |
| 22 | Period(2025-06-02..2025-06-08) |
| 23 | Period(2025-06-09..2025-06-15) |
| 24 | Period(2025-06-16..2025-06-22) |
| 25 | Period(2025-06-23..2025-06-29) |
| 26 | Period(2025-06-30..2025-07-06) |
| 27 | Period(2025-07-07..2025-07-13) |
| 28 | Period(2025-07-14..2025-07-20) |
| 29 | Period(2025-07-21..2025-07-27) |
| 30 | Period(2025-07-28..2025-08-03) |
| 31 | Period(2025-08-04..2025-08-10) |
| 32 | Period(2025-08-11..2025-08-17) |
| 33 | Period(2025-08-18..2025-08-24) |
| 34 | Period(2025-08-25..2025-08-31) |
| 35 | Period(2025-09-01..2025-09-07) |
| 36 | Period(2025-09-08..2025-09-14) |
| 37 | Period(2025-09-15..2025-09-21) |
| 38 | Period(2025-09-22..2025-09-28) |
| 39 | Period(2025-09-29..2025-09-30) |

Period.ensure

Period.ensure tries to interpret its argument as a Period and returns it; otherwise it throws an ArgumentError exception:

  • if the argument responds to the to_period method, it invokes that on the argument and returns it;
  • if the argument is a String, it uses Period.parse_phrase to try to interepret it as a Period;
  • if it is already a Period, it just returns the argument;
  • otherwise, it throws an ArgumentError exception.
   class ContainingMonth
     def initialize(dat)
       @dat = Date.ensure(dat)
     end

     def to_period
       Period.month_containing(@dat)
     end
   end

   cm = ContainingMonth.new('2025-09-22')
   Period.ensure(cm)
  Period(2025-09-01..2025-09-30)
  Period.ensure('from 2016 to 2018-3Q')
Period(2016-01-01..2018-09-30)
  Period.ensure(Period.new('2016-01-02', '2017-09-29'))
Period(2016-01-02..2017-09-29)

Conversion

#to_range

Period#to_range converts the Period to a Range with limits first..last.

  [Period.this_year.to_range.class, Period.this_year.to_range.to_s]
| Range | 2026-01-01..2026-12-31 |

#to_s

Period#to_s does String conversion but using compact notation for years, halves, quarters, and months if possible; otherwise, it gives first and last explicitly:

  specs = [
    'from this_year',
    'from 2026-2H',
    'from 2026-3Q',
    'from 2026-10',
    'from 2026-10 to 2026-10-30'
  ]
  tab = []
  tab << ['Spec', '#to_s']
  tab << nil
  specs.each do |s|
    pd = Period.parse_phrase(s).first
    tab << [s, pd.to_s]
  end
  tab
| Spec                       | #to_s                    |
|----------------------------+--------------------------|
| from this_year             | 2026                     |
| from 2026-2H               | 2026-2H                  |
| from 2026-3Q               | 2026-3Q                  |
| from 2026-10               | 2026-10                  |
| from 2026-10 to 2026-10-30 | 2026-10-01 to 2026-10-30 |

#tex_quote

Period#tex_quote formats a period in a way suitable for TeX or LaTeX. Mainly, this causes it to use an "en-dash" to separate the end points and hyphens to separate date components.

  specs = [
    'from this_year',
    'from 2026-2H',
    'from 2026-3Q',
    'from 2026-10',
    'from 2026-10 to 2026-10-30'
  ]
  tab = []
  tab << ['Spec', '#to_s']
  tab << nil
  specs.each do |s|
    pd = Period.parse_phrase(s).first
    tab << [s, pd.tex_quote]
  end
  tab
| Spec                       | #to_s                  |
|----------------------------+------------------------|
| from this_year             | 2026-01-01--2026-12-31 |
| from 2026-2H               | 2026-07-01--2026-12-31 |
| from 2026-3Q               | 2026-07-01--2026-09-30 |
| from 2026-10               | 2026-10-01--2026-10-31 |
| from 2026-10 to 2026-10-30 | 2026-10-01--2026-10-30 |

Comparison

The Period class includes Comparable so periods can be compared directly. Period are compared by first, and if those are the same, then by last, and those using normal Date comparison.

  spec_pairs = [
    ['from 2026', 'from 2026-1H'],
    ['from 2026', 'from 2026-2H'],
    ['from 2016-05', 'from 2016-05 to 2016-06'],
    ['from 2026', 'from 2026-2H'],
    ['from 2026', 'from 2025'],
    ['from 2010-09', 'from 2010-09'],
  ]
  tab = []
  tab << ['Period1', 'Period2', 'Period1 <=> Period2']
  tab << nil
  spec_pairs.each do |s1, s2|
    p1 = Period.parse_phrase(s1).first
    p2 = Period.parse_phrase(s2).first
    tab << [p1.to_s, p2.to_s, p1 <=> p2]
  end
  tab
| Period1 | Period2                  | Period1 <=> Period2 |
|---------+--------------------------+---------------------|
|    2026 | 2026-1H                  | 1                   |
|    2026 | 2026-2H                  | -1                  |
| 2016-05 | 2016-05-01 to 2016-06-30 | -1                  |
|    2026 | 2026-2H                  | -1                  |
|    2026 | 2025                     | 1                   |
| 2010-09 | 2010-09                  | 0                   |

Enumeration

#each

Period includes Enumerable and defines an #each method that iterates through each day in the period:

pd = Period.parse('2024-02')
n = 0
tab = []
tab << ['N', 'Day']
tab << nil
pd.each do |day|
  tab << [n += 1, day.iso]
end
tab
|  N | Day        |
|----+------------|
|  1 | 2024-02-01 |
|  2 | 2024-02-02 |
|  3 | 2024-02-03 |
|  4 | 2024-02-04 |
|  5 | 2024-02-05 |
|  6 | 2024-02-06 |
|  7 | 2024-02-07 |
|  8 | 2024-02-08 |
|  9 | 2024-02-09 |
| 10 | 2024-02-10 |
| 11 | 2024-02-11 |
| 12 | 2024-02-12 |
| 13 | 2024-02-13 |
| 14 | 2024-02-14 |
| 15 | 2024-02-15 |
| 16 | 2024-02-16 |
| 17 | 2024-02-17 |
| 18 | 2024-02-18 |
| 19 | 2024-02-19 |
| 20 | 2024-02-20 |
| 21 | 2024-02-21 |
| 22 | 2024-02-22 |
| 23 | 2024-02-23 |
| 24 | 2024-02-24 |
| 25 | 2024-02-25 |
| 26 | 2024-02-26 |
| 27 | 2024-02-27 |
| 28 | 2024-02-28 |
| 29 | 2024-02-29 |

#size

Period#size returns the number of days in the period.

Period.parse('2024-02').size
29

Chunking

FatPeriod recognizes several calendar sub-period types than the standard libraries do:

  • day
  • week
  • biweek
  • semimonth
  • month
  • bimonth
  • quarter
  • half
  • year

FatPeriod refers to these special kinds of periods as "chunks", and they are often useful in financial applications.

Period.<chunk>_containing(date)

For each chunk, FatPeriod provides a method for returning the Period of the size of the given chunk containing a given date. For example, to find the calendar quarter containing '2016-08-04', you can call Period.quarter_containing('2016-08-04') and get the period 2016-3Q.

  chunks = %w(
    day
    week
    biweek
    semimonth
    month
    bimonth
    quarter
    half
    year
)
tab = []
tab << ['Chunk Size', 'Containing Period']
tab << nil
chunks.each do |ck|
  meth = "#{ck}_containing".to_sym
  pd = Period.send(meth, '2016-08-04').to_s
  tab << [ck, pd.to_s]
end
tab
| Chunk Size | Containing Period        |
|------------+--------------------------|
| day        | 2016-08-04 to 2016-08-04 |
| week       | 2016-08-01 to 2016-08-07 |
| biweek     | 2016-08-01 to 2016-08-14 |
| semimonth  | 2016-08-01 to 2016-08-15 |
| month      | 2016-08                  |
| bimonth    | 2016-07-01 to 2016-08-31 |
| quarter    | 2016-3Q                  |
| half       | 2016-2H                  |
| year       | 2016                     |

Period also provides several related methods that return the chunk-sized period containing today's date:

  chunks = %w(
    day
    week
    biweek
    semimonth
    month
    bimonth
    quarter
    half
    year
)
tab = []
tab << ['Chunk Size', 'Current Period']
tab << nil
chunks.each do |ck|
  meth = "this_#{ck}".to_sym
  pd = Period.send(meth).to_s
  tab << [ck, pd.to_s]
end
tab
| Chunk Size | Current Period           |
|------------+--------------------------|
| day        | 2026-11-05 to 2026-11-05 |
| week       | 2026-11-02 to 2026-11-08 |
| biweek     | 2026-10-26 to 2026-11-08 |
| semimonth  | 2026-11-01 to 2026-11-15 |
| month      | 2026-11                  |
| bimonth    | 2026-11-01 to 2026-12-31 |
| quarter    | 2026-4Q                  |
| half       | 2026-2H                  |
| year       | 2026                     |

#chunk_sym and #chunk_name

A Period can determine if it is a chunk with the #chunk_sym method. It's first and last dates correspond to a chunk boundary, it returns a Symbol for its chunks size, or the symbol :irregular otherwise. A similar method, #chunk_name, returns a String name of the chunk:

Date.beginning_of_week = :sunday
pds = [
Period.new('2016-02-01', '2016-02-29'),
Period.new('2016-02-01', '2016-02-28'),
Period.new('2017-02-01', '2017-02-28'),
Period.new('2017-01-01', '2017-02-28'),
Period.new('2016-01-01', '2016-03-31'),
Period.new('2016-03-20', '2016-03-26'),
Period.new('2016-01-02', '2016-04-01'),
]
tab = []
tab << ['First', 'Last', 'Chunk']
tab << nil
pds.each do |pd|
  tab << [pd.first.iso, pd.last.iso, pd.chunk_sym]
end
tab
| First      | Last       | Chunk      |
|------------+------------+------------|
| 2016-02-01 | 2016-02-29 | :month     |
| 2016-02-01 | 2016-02-28 | :irregular |
| 2017-02-01 | 2017-02-28 | :month     |
| 2017-01-01 | 2017-02-28 | :bimonth   |
| 2016-01-01 | 2016-03-31 | :quarter   |
| 2016-03-20 | 2016-03-26 | :week      |
| 2016-01-02 | 2016-04-01 | :irregular |

#chunks(size: :month, partial_first: true, partial_last: true, round_up_last: false)

You may want to divide a year into months, or a quarter into semi-months. For this FatTable provides Period#chunks. By default, the first and last chunks will be partial, the first starting at Period#first regardless of whether it is a full chunk and the last ending at Period#last regardless of whether it is a full chunk. But this can be altered at the cost of not fully spanning the subject Period.

  • partial_first: if set false, the first chunk will be a full-sized chunk at the possible cost of starting later than Period#first; it is true by default.
  • partial_last: if set false, the last chunk will be a full-sized chunk at the possible cost of ending earlier than Period#last; it is true by default.
  • round_up_last: if set true, the last chunk returned may extend beyond Period#last if it needs to in order to make it whole; it is false by default.

Since weeks do not necessarily align with calendar quarters, we get a partial first and last week by default:

  Period.parse('2026-3Q').chunks(size: :week).map {|m| [m]}
| Period | (2026-07-01..2026-07-04) |
| Period | (2026-07-05..2026-07-11) |
| Period | (2026-07-12..2026-07-18) |
| Period | (2026-07-19..2026-07-25) |
| Period | (2026-07-26..2026-08-01) |
| Period | (2026-08-02..2026-08-08) |
| Period | (2026-08-09..2026-08-15) |
| Period | (2026-08-16..2026-08-22) |
| Period | (2026-08-23..2026-08-29) |
| Period | (2026-08-30..2026-09-05) |
| Period | (2026-09-06..2026-09-12) |
| Period | (2026-09-13..2026-09-19) |
| Period | (2026-09-20..2026-09-26) |
| Period | (2026-09-27..2026-09-30) |

But we can suppress the partials at the cost of not spanning the whole quarter:

  Period.parse('2026-3Q').chunks(size: :week, partial_first: false, partial_last: false).map {|m| [m]}
| Period | (2026-07-05..2026-07-11) |
| Period | (2026-07-12..2026-07-18) |
| Period | (2026-07-19..2026-07-25) |
| Period | (2026-07-26..2026-08-01) |
| Period | (2026-08-02..2026-08-08) |
| Period | (2026-08-09..2026-08-15) |
| Period | (2026-08-16..2026-08-22) |
| Period | (2026-08-23..2026-08-29) |
| Period | (2026-08-30..2026-09-05) |
| Period | (2026-09-06..2026-09-12) |
| Period | (2026-09-13..2026-09-19) |
| Period | (2026-09-20..2026-09-26) |

With round_up_last set true, the last chunk overflows the subject Period's bounds if needed to make it a whole week:

  Period.parse('2026-3Q').chunks(size: :week, round_up_last: true).map {|m| [m]}
| Period | (2026-07-01..2026-07-04) |
| Period | (2026-07-05..2026-07-11) |
| Period | (2026-07-12..2026-07-18) |
| Period | (2026-07-19..2026-07-25) |
| Period | (2026-07-26..2026-08-01) |
| Period | (2026-08-02..2026-08-08) |
| Period | (2026-08-09..2026-08-15) |
| Period | (2026-08-16..2026-08-22) |
| Period | (2026-08-23..2026-08-29) |
| Period | (2026-08-30..2026-09-05) |
| Period | (2026-09-06..2026-09-12) |
| Period | (2026-09-13..2026-09-19) |
| Period | (2026-09-20..2026-09-26) |
| Period | (2026-09-27..2026-10-03) |

Set Operations

Another question one might want to ask of a Period is how it relates to another Period. Does it fully contain another? Is it a sub-period of another, and so-forth. Since these resemble the same sorts of questions one might ask of sets of numbers, these are called "set operations" on Periods.

#subset_of?(other)

Is this Period wholly contained within the other Period?

 Period.parse('2026-1Q').subset_of?(Period.parse('2026'))
true

Note that every Period is it's own subset:

 Period.parse('2026').subset_of?(Period.parse('2026'))
true
 Period.parse('2026').subset_of?(Period.parse('2026-2Q'))
false

#proper_subset_of?(other)

Is this Period wholly contained within the other Period but not identical to it?

 Period.parse('2026-1Q').proper_subset_of?(Period.parse('2026'))
true

Note that every Period is not it's own proper subset:

 Period.parse('2026').proper_subset_of?(Period.parse('2026'))
false

#superset_of(other)

Does this Period wholly contain other Period?

 Period.parse('2026-1Q').superset_of?(Period.parse('2026'))
false
 Period.parse('2026').superset_of?(Period.parse('2026-2H'))
true

Note that every Period is it's own superset:

 Period.parse('2026').superset_of?(Period.parse('2026'))
true

#proper_superset_of(other)

Does this Period wholly contain other Period without being identical to it?

 Period.parse('2026').proper_superset_of?(Period.parse('2026-2Q'))
true

Note that every Period is not it's own proper superset:

 Period.parse('2026').proper_superset_of?(Period.parse('2026'))
false

#intersection(other)

Return a new Period that is contained in both the subject Period and other.

 Period.parse('2026').intersection(Period.parse_phrase('from 2025-33W to 2026-23W').first)
Period(2026-01-01..2026-06-07)

The & operator is equivalent.

 Period.parse('2026') & Period.parse_phrase('from 2025-33W to 2026-23W').first
Period(2026-01-01..2026-06-07)

As is the method narrow_to.

 Period.parse('2026').narrow_to(Period.parse_phrase('from 2025-33W to 2026-23W').first)
Period(2026-01-01..2026-06-07)

Return nil if there is no intersection:

 Period.parse('2026').intersection(Period.parse('2024-3Q'))
nil

#union(other)

If two Periods either overlap or are contiguous, you can return a Period that spans both:

 Period.parse('2026').union(Period.parse_phrase('from 2025-33W to 2026-23W').first)
Period(2025-08-11..2026-12-31)

The + operator is equivalent.

 Period.parse('2026') + Period.parse_phrase('from 2025-33W to 2026-23W').first
Period(2025-08-11..2026-12-31)

Return nil if there is no overlap or contiguity:

 Period.parse('2026').union(Period.parse('2024-3Q'))
nil

#difference(other)

Return an Array of Periods representing the subject Period with any overlap with other excluded. If there is no overlap, return the subject Period.

 Period.parse('2015-1Q').difference(Period.parse('2015-02')).map {|p| [p.to_s]}
| 2015-01 |
| 2015-03 |
 Period.parse('2015-1Q').difference(Period.parse('2015-08')).map {|p| [p.to_s]}
| 2015-1Q |

The operator - can be used as well:

 (Period.parse('2015-1Q') - Period.parse('2015-02')).map {|p| [p.to_s]}
| 2015-01 |
| 2015-03 |

Coverage

#contains?(date)

Return whether the subject Period contains the given Date.

  Period.parse('2026-2Q').contains?('2026-04-15')
true
  Period.parse('2026-2Q').contains?('2026-08-15')
false

Period.overlaps_among?(periods)

This class method takes an Array of Periods and returns whether the given periods have any overlaps with one another.

#overlaps_among?

Similar to Period.overlaps_among except that it returns true only if any of the overlaps occur within the subject Period.

#spanned_by(periods)

Returns whether the given Array of Periods "span" the subject Period, that is, whether they collectively cover the subject Period with no overlaps and no gaps.

#gaps

Returns an Array of Period~s representing the gaps within the subject ~Period not covered by the given Array of Periods. Overlaps among the periods do not affect the result nor do gaps outside the range of the subject Period. Ordering among the given periods does not matter.

Interest Day-count fraction (#year_fraction)

For interest-related calculations, the methods by which accrued interest is allocated to a partial Period are numerous and subtle. Rather than solve this problem over-and-over, FatPeriod aims to implement a single method that solves this problem once-and-for-all.

The dates that correspond to the notation in Wikipedia's Day count convention article, which was used as a reference for FatPeriod's implementation, are as follows:

  • first is Date1, the start of accrual.
  • date2 is Date2, the payment or settlement date, supplied as a Date or a date string. It must fall within the Period, including its endpoints.
  • last is Date3, the next coupon payment date. For ICMA, construct the Period with consecutive coupon boundaries.

Period#year_fraction returns a BigDecimal factor for calculating interest from first to a given payment or settlement date. Usually this is a fraction of a year: multiply the principal by the annual rate and this factor to calculate accrued interest. The default convention is 30/360 US (convention: 1).

period.year_fraction(date2, convention: 1, eom: true, maturity_date: nil)

Day counts use elapsed days, without adding one as Period#size does. For example, January 1 to July 1 is the reference period for a coupon paid on July 1; use July 1 as last, rather than June 30. Passing last as the settlement date calculates the full coupon's factor.

period = Period.new('2024-01-01', '2024-07-01')
pay_date = '2024-04-01'
principal = BigDecimal('1000')
rate = BigDecimal('0.05')

tab =
  [['Principal', principal.to_s('F')],
   ['Rate', rate.to_s('F')],
   ['Period', period.to_s],
   ['Payment Date', pay_date]]
tab
| Principal    |                   1000.0 |
| Rate         |                     0.05 |
| Period       | 2024-01-01 to 2024-07-01 |
| Payment Date |               2024-04-01 |
tab2 = []
tab2 << ['Convention', 'Factor', 'Interest']
tab2 << nil
0.upto(11) do |conv|
  factor = period.year_fraction(pay_date, convention: conv)
  interest = principal * rate * factor
  tab2 << [conv, factor.round(4).to_s('F'), interest.round(2).to_s('F')]
end
tab2
| Convention | Factor | Interest |
|------------+--------+----------|
| 0          |   0.25 |     12.5 |
| 1          |   0.25 |     12.5 |
| 2          |   0.25 |     12.5 |
| 3          |   0.25 |     12.5 |
| 4          |   0.25 |     12.5 |
| 5          | 0.2486 |    12.43 |
| 6          | 0.2493 |    12.47 |
| 7          | 0.2528 |    12.64 |
| 8          |   0.25 |     12.5 |
| 9          | 0.2486 |    12.43 |
| 10         | 0.2486 |    12.43 |
| 11         |    1.0 |     50.0 |

Choosing a convention

The convention numbers are specific to FatPeriod; they are not Excel's YEARFRAC basis numbers. Supply convention: 0 explicitly for Bond Basis. The ISDA references below are to Section 4.16 of the 2006 ISDA Definitions.

Convention Name Reference
0 30/360 Bond Basis ISDA 4.16(f)
1 30/360 US (default) 4.16(f), plus US February rules
2 30E/360 ISDA 4.16(g)
3 30E/360 ISDA ISDA 4.16(h)
4 Actual/Actual ICMA ISDA 4.16(c); ICMA Rule 251
5 Actual/Actual ISDA ISDA 4.16(b)
6 Actual/365 Fixed ISDA 4.16(d)
7 Actual/360 ISDA 4.16(e)
8 Actual/364 Wikipedia's Actual/364 section
9 Actual/365L Wikipedia's Actual/365L section
10 Actual/Actual AFB Wikipedia's AFB discussion
11 1/1 ISDA 4.16(a)

For convention 1, eom: true (the default) applies the February end-of-month rules for investments that pay at month end. Set eom: false to omit those February adjustments. The remaining 30/360 adjustments still apply.

For convention 3, maturity_date: accepts a Date or date string and identifies the investment's final maturity. It is irrelevant for the other conventions and is nil by default. Under convention 3, when settlement (i.e., date2) is that date and is the last day of February, its day number is left unchanged. Otherwise the usual month-end adjustment applies.

  final_coupon = Period.new('2023-08-31', '2024-02-29')
  ordinary = final_coupon.year_fraction('2024-02-29', convention: 3)
  at_maturity = final_coupon.year_fraction(
    '2024-02-29', convention: 3, maturity_date: '2024-02-29'
  )
  [ordinary.to_s('F'), at_maturity.round(10).to_s('F')]
| 0.5 | 0.4972222222 |

Actual-day conventions and boundaries

ICMA (4) divides elapsed days by the product of payment frequency and elapsed days in the full coupon period. Frequency is inferred from the full period's length. For example, both a full 181-day half-year coupon and a full 184-day half-year coupon have a factor of 0.5, but their daily accruals differ.

  coupon = Period.new('2024-01-01', '2024-07-01')
  partial = coupon.year_fraction('2024-04-01', convention: 4)
  full = coupon.year_fraction(coupon.last, convention: 4)
  [partial.to_s('F'), full.to_s('F')]
| 0.25 | 0.5 |

ICMA supports regular coupon periods only; it does not construct notional coupon schedules for irregular first or final coupons. Frequency inference allows the same 10% length tolerance as chunk_name for monthly and longer periods. An unrecognizable length raises ArgumentError for conventions that require frequency (4 and 9).

ISDA Actual/Actual (5) splits the elapsed interval at calendar-year boundaries, using 365 or 366 for each portion. Conventions 6, 7, and 8 use fixed denominators of 365, 360, and 364 respectively.

Actual/365L (9) follows the Wikipedia article's settlement-date rule: for annual payments, it uses 366 if February 29 falls after first and on or before settlement, otherwise 365. For other frequencies, it uses the number of days in the settlement year. The full period determines frequency, not the leap-day test interval.

AFB (10) counts complete years backwards from settlement, then calculates the remaining initial fraction. It uses the ISDA backward-counting February adjustment described in the article: a February 28 anniversary moves to February 29 when the preceding year is a leap year. The remaining fraction uses 366 only when it includes February 29, counting its start but excluding its end.

Equal start and settlement dates return zero for conventions 0 through 10. Convention 11 (1/1) always returns one, even for equal dates: it applies the full contractual rate without prorating for time. Invalid convention numbers or settlement dates outside the Period raise ArgumentError.

Sources

Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ddoherty03/fat_table.