pandas_market_calendars package

Submodules

pandas_market_calendars.calendar_registry module

pandas_market_calendars.calendar_registry.get_calendar(name: str, open_time: time | None = None, close_time: time | None = None) MarketCalendar

Retrieves an instance of an MarketCalendar whose name is given.

Parameters:
  • name – The name of the MarketCalendar to be retrieved.

  • open_time – Market open time override as datetime.time object. If None then default is used.

  • close_time – Market close time override as datetime.time object. If None then default is used.

Returns:

MarketCalendar of the desired calendar.

pandas_market_calendars.calendar_registry.get_calendar_names() list[str]

All Market Calendar names and aliases that can be used in “factory” :return: list(str)

pandas_market_calendars.calendar_utils module

Utilities to use with market_calendars

exception pandas_market_calendars.calendar_utils.DateRangeWarning

Bases: UserWarning

Super Class to all Date_range Warning Types

exception pandas_market_calendars.calendar_utils.DisappearingSessionWarning

Bases: DateRangeWarning

Warning thrown when date_range is called with a timedelta that is larger than an entire session resulting in the session disappearing from the DatetimeIndex.

Only an issue when closed=’right’ and force_close = False

exception pandas_market_calendars.calendar_utils.InsufficientScheduleWarning

Bases: DateRangeWarning

Warning thrown when a date_range() call is made with a requested number of periods, or start-date / end-date that exceed what was provided in the given schedule.

If a Schedule has an insufficient start and end date then this warning is thrown twice.

If this warning is thrown when date_range is called with a number of desired periods, then the desired start/end date is an approximate value. This ‘approximation’ is biased to overestimate the needed start/end time by about 1 week. This is done to limit the edge cases where this warning could get thrown multiple times in a row.

exception pandas_market_calendars.calendar_utils.MissingSessionWarning

Bases: DateRangeWarning

Warning thrown when a date_range() call is made with a requested session, but lacks the necessary columns. When this warning is ignored the returned datetimeindex will simply lack the relevant sessions

e.g. ‘pre’ Session requested and schedule lacks ‘pre’ and/or ‘market_open’ column

exception pandas_market_calendars.calendar_utils.OverlappingSessionWarning

Bases: DateRangeWarning

Warning thrown when date_range is called with a timedelta that is larger than the gap between two sessions leading to them overlapping. This is only an issue when closed=’right’/’both’/None and force_close=None

For Example, the following raises a warning because the 10:00 Timestamp that is from the ‘pre’ session comes after the start of the 9:30 ‘RTH’ session, but belongs to the ‘pre’ session

>>> date_range(NYSE, "2h", "right", None, {"pre", "RTH"}, merge_adjacent=False)
>>> ['2020-01-02 06:00:00', '2020-01-02 08:00:00',
     '2020-01-02 10:00:00', '2020-01-02 11:30:00',
     '2020-01-02 13:30:00', '2020-01-02 15:30:00',
     '2020-01-02 17:30:00'],
This is particularly convoluted when close=’both’/None
>>> date_range(NYSE, "2h", "both", None, {"pre", "RTH"}, merge_adjacent=False)
>>> ['2020-01-02 04:00:00' (pre), '2020-01-02 06:00:00' (pre),
     '2020-01-02 08:00:00' (pre), '2020-01-02 09:30:00' (rth),
     '2020-01-02 10:00:00' (pre), '2020-01-02 11:30:00' (rth),
     '2020-01-02 13:30:00' (rth), '2020-01-02 15:30:00' (rth),
     '2020-01-02 17:30:00' (rth)],
pandas_market_calendars.calendar_utils.all_single_observance_rules(calendar: AbstractHolidayCalendar) List[Timestamp] | None

Returns a list of timestamps if the Calendar’s Rules are all single observance holidays, None Otherwise

pandas_market_calendars.calendar_utils.convert_freq(index: DatetimeIndex, frequency: str) pd.Index[Any]

Converts a DateTimeIndex to a new lower frequency

Parameters:
  • index – DateTimeIndex

  • frequency – frequency string

Returns:

DateTimeIndex

pandas_market_calendars.calendar_utils.date_range(schedule: DataFrame, frequency: str | Timedelta | int | float, closed: Literal['left', 'right', 'both'] | None = 'right', force_close: bool | None = True, session: Literal['pre', 'post', 'RTH', 'pre_break', 'post_break', 'ETH', 'break', 'closed', 'closed_masked'] | Iterable[Literal['pre', 'post', 'RTH', 'pre_break', 'post_break', 'ETH', 'break', 'closed', 'closed_masked']] | None = None, merge_adjacent: bool = True, start: str | Timestamp | int | float | None = None, end: str | Timestamp | int | float | None = None, periods: int | None = None) DatetimeIndex

Interpolates a Market’s Schedule at the desired frequency and returns the result as a DatetimeIndex. This function is only valid for periods less than 1 Day, for longer periods use date_range_htf().

Note: The slowest part of this function is by far generating the necessary schedule (which in turn is limited by pandas’ date_range() function). If speed is a concern, store and update the schedule as needed instead of generating it every time.

WARNINGS SYSTEM:

*There are multiple edge-case warnings that are thrown by this function. See the Docstrings of each warning for more info. (DateRangeWarning, InsufficientScheduleWarning, MissingSessionWarning, OverlappingSessionWarning, DisappearingSessionWarning)

*The thrown warnings can be ignored or escalated into catchable errors by using the filter_date_range_warnings() function.

parse_missing_session_warning() & parse_insufficient_schedule_warning() exist to easily process the warnings those warnings if they are escalated into errors.

PARAMETERS:

Parameters:
  • schedule – Schedule of a calendar which includes all the columns necessary for the desired sessions.

  • frequency – String, Int/float (seconds) or pd.Timedelta that represents the desired interval of the date_range. Intervals larger than 1D are not supported.

  • closed – the way the intervals are labeled ‘right’: use the end of the interval ‘left’: use the start of the interval None / ‘both’: use the end of the interval but include the start of the first interval

  • force_close – How the last value of a trading session is handled True: guarantee that the close of the trading session is the last value False: guarantee that there is no value greater than the close of the trading session None: leave the last value as it is calculated based on the closed parameter

  • session

    A str representing a single session or an Iterable of the following Sessions. RTH: The Default Option. This is [Market_open, Market_close], if the schedule includes a

    break then the break is excluded from the returned datetime index.

    ETH: [pre, market_open] & [market_close, post] pre: [pre, market_open] post: [market_close, post] break: [break_start, break_end] pre_break: [market_open, break_start] post_break: [break_end, market_close] closed: [market_close, market_open (of the next day)] If ETH market times are given then

    this will be [post, pre (of the next day)] instead. The last session will end at Midnight of the timezone the schedule is given in.

    closed_masked: Same as closed, but Weekends & Holidays are ignored. Instead, the Datetime

    index stops at Midnight on the trading day before the break and resumes at midnight prior to the next trading day. **Note: This is Midnight of the Timezone the schedule is given in, not Midnight of the exchange’s tz since the exchange’s tz is not known.

  • merge_adjacent

    Bool representing if adjacent sessions should be merged into a single session. For Example, NYSE w/ session={‘RTH’, ‘ETH’}, frequency=2h, closed=left, force_close=False merge_adjacent == True => [pre, post]

    >>> ['2020-01-02 04:00:00', '2020-01-02 06:00:00',
         '2020-01-02 08:00:00', '2020-01-02 10:00:00',
         '2020-01-02 12:00:00', '2020-01-02 14:00:00',
         '2020-01-02 16:00:00', '2020-01-02 18:00:00']
    
    merge_adjacent == False => [pre, market_open] & [market_open, market_close] & [market_close, post]
    >>> ['2020-01-02 04:00:00', '2020-01-02 06:00:00',
         '2020-01-02 08:00:00', '2020-01-02 09:30:00',
         '2020-01-02 11:30:00', '2020-01-02 13:30:00',
         '2020-01-02 15:30:00', '2020-01-02 16:00:00',
         '2020-01-02 18:00:00']
    

    merge_adjacent=False re-aligns the timestamps to the session, but this results in the difference between timestamps not always equaling the desired frequency.

  • start

    Optional [String, Int/float (POSIX seconds) or pd.Timestamp] of the desired start time. :If left as None then the start-time of the the Schedule is used. :If no TZ info is given it will be interpreted in the same timezone as the first column of the schedule :Start can be a Day and Time, but the returned index will still be aligned to the underlying schedule. e.g. Session = [9:30am, 12pm], frequency=7min, start=9:45am. Underlying session

    = [9:30, 9:37, 9:44, 9:51, …] => returned DatetimeIndex = [9:51, …]

  • end – Optional [String, Int/float (POSIX seconds) or pd.Timestamp] of the desired end time. :If left as None then the end-time of the the Schedule is used. :If no TZ info is given it will be interpreted in the same timezone as the first column **Note: The time given is an absolute value. i.e. end=”2020-01-01” == “2020-01-01 00:00” returning times prior to Midnight of “2019-12-31”, not to the EOD of “2020-01-01”

  • periods

    Optional Integer number of periods to return. If a Period count, Start time, and End time are given the period count is ignored. None: Period count is ignored. Returned index is all periods in [Start, End] Int: # of periods to return. By default, this is the first N periods following the start.

    If an end time is given then this is the N periods prior to the End Time (inclusive).

    CAVEAT: When Force_close == False & closed == ‘right’/’both’ the number of periods returned

    may be less than the parameter given.

Returns:

pd.DatetimeIndex of datetime64[ns, TZ-Aware]

pandas_market_calendars.calendar_utils.date_range_htf(cal: CustomBusinessDay, frequency: str | Timedelta | int | float, start: str | Timestamp | int | float | None = None, end: str | Timestamp | int | float | None = None, periods: int | None = None, closed: Literal['left', 'right'] | None = 'right', *, day_anchor: Literal['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] = 'SUN', month_anchor: Literal['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] = 'JAN') DatetimeIndex

Returns a Normalized DatetimeIndex from the start-date to End-Date for Time periods of 1D and Higher.

Unless using a custom calendar, it is advised to call the date_range_htf() method of the desired calendar. This is because default_anchors may change, or a single calendar may not be sufficient to model a market.

For example, NYSE has two calendars: The first covers pre-1952 where saturdays were trading days. The second covers post-1952 where saturdays are closed.

PARAMETERS:

Parameters:
  • cal – CustomBusinessDay Calendar associated with a MarketCalendar. This can be retrieved by calling the holidays() method of a MarketCalendar.

  • frequency

    String, Int/float (POSIX seconds) or pd.Timedelta of the desired frequency. :Must be Greater than ‘1D’ and an integer multiple of the base frequency (D, W, M, Q, or Y) :Important Note: Ints/Floats & Timedeltas are always considered as ‘Open Business Days’,

    ’2D’ == Every Other business Day, ‘3D’ == Every 3rd B.Day, ‘7D’ == Every 7th B.Day

    :Higher periods (passed as strings) align to the beginning or end of the relevant period :i.e. ‘1W’ == First/[Last] Trading Day of each Week, ‘1Q’ == First/[Last] Day of every Quarter

  • start – String, Int/float (POSIX seconds) or pd.Timestamp of the desired start time. :The Time & Timezone information is ignored. Only the Normalized Day is considered.

  • end – String, Int/float (POSIX seconds) or pd.Timestamp of the desired start time. :The Time & Timezone information is ignored. Only the Normalized Day is considered.

  • periods – Optional Integer number of periods to return. If a Period count, Start time, and End time are given the period count is ignored.

  • closed – Literal[‘left’, ‘right’]. Method used to close each range. :Left: First open trading day of the Session is returned (e.g. First Open Day of The Month) :right: Last open trading day of the Session is returned (e.g. Last Open Day of The Month) :Note, This has no effect when the desired frequency is a number of days.

  • day_anchor

    Day to Anchor the start of the Weekly timeframes to. Default ‘SUN’. : To get the First/Last Days of the trading Week then the Anchor needs to be on a day the relevant

    market is closed.

    : This can be set so that a specific day each week is returned. : freq=’1W’ & day_anchor=’WED’ Will return Every ‘WED’ when the market is open, and nearest day

    to the left or right (based on ‘closed’) when the market is closed.

    Options: [“SUN”, “MON”, “TUE”, “WED”, “THU”, “FRI”, “SAT”]

  • month_anchor – Month to Anchor the start of the year to for Quarter and yearly timeframes. : Default ‘JAN’ for Calendar Quarters/Years. Can be set to ‘JUL’ to return Fiscal Years Options: [“JAN”, “FEB”, “MAR”, “APR”, “MAY”, “JUN”, “JUL”, “AUG”, “SEP”, “OCT”, “NOV”, “DEC”]

pandas_market_calendars.calendar_utils.filter_date_range_warnings(action: ~typing.Literal['error', 'ignore', 'always', 'default', 'once'], source: ~typing.Iterable[~typing.Type[~pandas_market_calendars.calendar_utils.DateRangeWarning]] | ~typing.Type[~pandas_market_calendars.calendar_utils.DateRangeWarning] = <class 'pandas_market_calendars.calendar_utils.DateRangeWarning'>) None

Adjust the behavior of the date_range() warnings to the desired action.

Parameters:
  • action

    • The desired change to the warning behavior

    ’error’: Escalate Warnings into Errors ‘ignore’: Silence Warning Messages ‘once’: Only display a message of the given category once ‘default’: Reset the behavior of the given warning category ‘always’: Always show the Warning of a given category

  • source

    • The Category/Categories to apply the action to. Can be a single Warning or a list of warnings

    default: DateRangeWarning (All Warnings) Warning Types: MissingSessionWarning, OverlappingSessionWarning,

    DisappearingSessionWarning, InsufficientScheduleWarning

pandas_market_calendars.calendar_utils.is_single_observance(holiday: Holiday) Timestamp | None

Returns the Date of the Holiday if it is only observed once, None otherwise.

pandas_market_calendars.calendar_utils.mark_session(schedule: DataFrame, timestamps: DatetimeIndex, label_map: Dict[str, Any] | None = None, *, closed: Literal['left', 'right'] = 'right') Series

Return a Series that denotes the trading session of each timestamp in a DatetimeIndex. The returned Series’s Index is the provided Datetime Index, the Series’s values are the timestamps’ corresponding session.

PARAMETERS:

Parameters:
  • schedule – The market schedule to check the timestamps against. This Schedule must include all of the trading days that are in the provided DatetimeIndex of timestamps. Note: The columns need to be sorted into ascending order, if not, then an error will be raised saying the bins must be in ascending order.

  • timestamps – A DatetimeIndex of Timestamps to check. Must be sorted in ascending order.

  • label_map

    Optional mapping of Dict[str, Any] to change the values returned in the series. The keys of the given mapping should match the keys of the default dict, but the values can be anything. A subset of mappings may also be provided, e.g. {‘closed’:-1} will only change the label of the ‘closed’ session. All others will remain the default label.

    >>> Default Mapping == {
        "pre": "pre",
        "rth_pre_break": "rth",     # When the Schedule has a break
        "rth": "rth",               # When the Schedule doesn't have a break
        "break": "break",           # When the Schedule has a break
        "rth_post_break": "rth",    # When the Schedule has a break
        "post": "post",
        "closed": "closed",
    }
    

  • closed – Which side of each interval should be closed (inclusive) left: == [start, end) right: == (start, end]

pandas_market_calendars.calendar_utils.merge_schedules(schedules: List[DataFrame], how: Literal['outer', 'inner'] = 'outer') DataFrame

Given a list of schedules will return a merged schedule. The merge method (how) will either return the superset of any datetime when any schedule is open (outer) or only the datetime where all markets are open (inner)

CAVEATS:
  • This does not work for schedules with breaks, the break information will be lost.

  • Only “market_open” and “market_close” are considered, other market times are not yet supported.

Parameters:
  • schedules – list of schedules

  • how – outer or inner

Returns:

schedule DataFrame

pandas_market_calendars.calendar_utils.parse_insufficient_schedule_warning(err: InsufficientScheduleWarning) Tuple[bool, Timestamp, Timestamp]

Parses the information from an Insufficient Schedule Warning. :returns Tuple[bool, pd.Timestamp, pd.Timestamp]:

bool: True == Range is missing from the start, False == Range missing from the end Timestamp 1: Start of missing range Timestamp 2: End of the missing range. Note: The Timestamps are always ordered (t1 <= t2) and do not overlap with the original schedule. If a supplemental schedule is generated it can be concatenated on without any overlapping indices. data

pandas_market_calendars.calendar_utils.parse_missing_session_warning(err: MissingSessionWarning) Tuple[Set[str], Set[str]]

Parses a Missing Session Warning’s Error Message. :returns Tuple[set[str], set[str]]:

Set #1: The Missing Sessions Set #2: The Missing Schedule Columns

pandas_market_calendars.class_registry module

class pandas_market_calendars.class_registry.ProtectedDict(*args: Any, **kwargs: Any)

Bases: dict

copy() a shallow copy of D
class pandas_market_calendars.class_registry.RegisteryMeta(name: str, bases: Any, attr: Any)

Bases: type

Metaclass used to register all classes inheriting from RegisteryMeta

pandas_market_calendars.exchange_calendar_asx module

pandas_market_calendars.exchange_calendar_bmf module

pandas_market_calendars.exchange_calendar_cfe module

pandas_market_calendars.exchange_calendar_cme module

pandas_market_calendars.exchange_calendar_eurex module

pandas_market_calendars.exchange_calendar_hkex module

pandas_market_calendars.exchange_calendar_ice module

pandas_market_calendars.exchange_calendar_jpx module

pandas_market_calendars.exchange_calendar_lse module

pandas_market_calendars.exchange_calendar_nyse module

pandas_market_calendars.exchange_calendar_ose module

pandas_market_calendars.exchange_calendar_six module

pandas_market_calendars.exchange_calendar_sse module

pandas_market_calendars.exchange_calendar_tase module

pandas_market_calendars.exchange_calendar_tsx module

pandas_market_calendars.exchange_calendar_xbom module

pandas_market_calendars.holidays_cn module

pandas_market_calendars.holidays_jp module

pandas_market_calendars.holidays_oz module

pandas_market_calendars.holidays_uk module

pandas_market_calendars.holidays_us module

pandas_market_calendars.jpx_equinox module

pandas_market_calendars.market_calendar module

class pandas_market_calendars.market_calendar.DEFAULT

Bases: object

class pandas_market_calendars.market_calendar.HolidayCalendar(*args: Any, start_date: Any = None, end_date: Any = None, **kwargs: Any)

Bases: AbstractHolidayCalendar

Holiday calendar with instance-local default bounds.

pandas’ AbstractHolidayCalendar.holidays() reads the pandas base class defaults when callers omit start/end. This class lets market calendars choose wider or narrower defaults without mutating pandas global state.

Initializes holiday object with a given set a rules. Normally classes just have the rules defined within them.

Parameters

namestr

Name of the holiday calendar, defaults to class name

rulesarray of Holiday objects

A set of rules used to create the holidays.

holidays(start: Any = None, end: Any = None, return_name: bool = False) Any

Returns a curve with holidays between start_date and end_date

Parameters

start : starting date, datetime-like, optional end : ending date, datetime-like, optional return_name : bool, optional

If True, return a series that has dates and holiday names. False will only return a DatetimeIndex of dates.

Returns

DatetimeIndex of holidays

class pandas_market_calendars.market_calendar.MarketCalendar(open_time: time | None = None, close_time: time | None = None)

Bases: object

An MarketCalendar represents the timing information of a single market or exchange. Unless otherwise noted all times are in UTC and use Pandas data structures.

Parameters:
  • open_time – Market open time override as datetime.time object. If None then default is used.

  • close_time – Market close time override as datetime.time object. If None then default is used.

add_time(market_time: str, times: Any, opens: Any = <class 'pandas_market_calendars.market_calendar.DEFAULT'>) None

Adds the specified market time to regular_market_times and makes the necessary adjustments.

Parameters:
  • market_time – the market_time to add

  • times – the time information

  • opens – see .change_time docstring

Returns:

None

property adhoc_holidays: List[Any]
Returns:

list of ad-hoc holidays

property break_end: time | None

Break time end. If None then there is no break

Returns:

time or None

break_end_on(date: Any) time | None
property break_start: time | None

Break time start. If None then there is no break

Returns:

time or None

break_start_on(date: Any) time | None
classmethod calendar_names() List[str]

All Market Calendar names and aliases that can be used in “factory” :return: list(str)

change_time(market_time: str, times: Any, opens: Any = <class 'pandas_market_calendars.market_calendar.DEFAULT'>) None

Changes the specified market time in regular_market_times and makes the necessary adjustments.

Parameters:
  • market_time – the market_time to change

  • times – new time information

  • opens

    whether the market_time is a time that closes or opens the market this is only needed if the market_time should be respected by .open_at_time True: opens False: closes None: consider it neither opening nor closing, don’t add to open_close_map (ignore in .open_at_time) DEFAULT: same as None, unless the market_time is in self.__class__.open_close_map. Then it will take

    the default value as defined by the class.

Returns:

None

clean_dates(start_date: Any, end_date: Any) Tuple[Timestamp, Timestamp]

Strips the inputs of time and time zone information

Parameters:
  • start_date – start date

  • end_date – end date

Returns:

(start_date, end_date) with just date, no time and no time zone

property close_offset: int
Returns:

close offset

property close_time: time

Default close time for the market

Returns:

time

close_time_on(date: Any) time | None
date_range_htf(frequency: str | Timedelta | int | float, start: str | Timestamp | int | float | None = None, end: str | Timestamp | int | float | None = None, periods: int | None = None, closed: Literal['left', 'right'] | None = 'right', *, day_anchor: Literal['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] = 'SUN', month_anchor: Literal['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] = 'JAN') DatetimeIndex

Returns a Normalized DatetimeIndex from the start-date to End-Date for Time periods of 1D and Higher.

PARAMETERS:

Parameters:
  • frequency

    String, Int/float (POSIX seconds) or pd.Timedelta of the desired frequency. :Must be Greater than ‘1D’ and an integer multiple of the base frequency (D, W, M, Q, or Y) :Important Note: Ints/Floats & Timedeltas are always considered as ‘Open Business Days’,

    ’2D’ == Every Other Buisness Day, ‘3D’ == Every 3rd B.Day, ‘7D’ == Every 7th B.Day

    :Higher periods (passed as strings) align to the beginning or end of the relevant period :i.e. ‘1W’ == First/[Last] Trading Day of each Week, ‘1Q’ == First/[Last] Day of every Quarter

  • start – String, Int/float (POSIX seconds) or pd.Timestamp of the desired start time. :The Time & Timezone information is ignored. Only the Normalized Day is considered.

  • end – String, Int/float (POSIX seconds) or pd.Timestamp of the desired start time. :The Time & Timezone information is ignored. Only the Normalized Day is considered.

  • periods – Optional Integer number of periods to return. If a Period count, Start time, and End time are given the period count is ignored.

  • closed – Literal[‘left’, ‘right’]. Method used to close each range. :Left: First open trading day of the Session is returned (e.g. First Open Day of The Month) :right: Last open trading day of the Session is returned (e.g. Last Open Day of The Month) :Note, This has no effect when the desired frequency is a number of days.

  • day_anchor

    Day to Anchor the start of the Weekly timeframes to. Default ‘SUN’. : To get the First/Last Days of the trading Week then the Anchor needs to be on a day the relevant

    market is closed.

    : This can be set so that a specific day each week is returned. : freq=’1W’ & day_anchor=’WED’ Will return Every ‘WED’ when the market is open, and nearest day

    to the left or right (based on ‘closed’) when the market is closed.

    Options: [“SUN”, “MON”, “TUE”, “WED”, “THU”, “FRI”, “SAT”]

  • month_anchor – Month to Anchor the start of the year to for Quarter and yearly timeframes. : Default ‘JAN’ for Calendar Quarters/Years. Can be set to ‘JUL’ to return Fiscal Years Options: [“JAN”, “FEB”, “MAR”, “APR”, “MAY”, “JUN”, “JUL”, “AUG”, “SEP”, “OCT”, “NOV”, “DEC”]

days_at_time(days: Any, market_time: str | time, day_offset: int = 0) Series

Create an index of days at time t, interpreted in timezone tz. The returned index is localized to UTC.

In the example below, the times switch from 13:45 to 12:45 UTC because March 13th is the daylight savings transition for US/Eastern. All the times are still 8:45 when interpreted in US/Eastern.

>>> import pandas as pd
... import datetime
... import pprint
>>> dts = pd.date_range("2016-03-12", "2016-03-14")
>>> dts_at_845 = days_at_time(dts, datetime.time(8, 45), "US/Eastern")
>>> pprint.pprint([str(dt) for dt in dts_at_845])
['2016-03-12 13:45:00+00:00',
 '2016-03-13 12:45:00+00:00',
 '2016-03-14 12:45:00+00:00']
Parameters:
  • days – DatetimeIndex An index of dates (represented as midnight).

  • market_time – datetime.time The time to apply as an offset to each day in days.

  • day_offset – int The number of days we want to offset @days by

Returns:

pd.Series of date with the time requested.

discontinued_market_times: ProtectedDict
early_closes(schedule: DataFrame) DataFrame

Get a DataFrame of the dates that are an early close.

Parameters:

schedule – schedule DataFrame

Returns:

schedule DataFrame with rows that are early closes

classmethod factory(name: str, *args: Any, **kwargs: Any) Any
Parameters:
  • cls(RegisteryMeta) – registration meta class

  • name(str) – name of class that needs to be instantiated

  • args(Optional(tuple)) – instance positional arguments

  • kwargs(Optional(dict)) – instance named arguments

Returns:

class instance

property full_name: str

Full name of the market

Returns:

string name

get_offset(market_time: str) int
get_special_times(market_time: str) List[Any]
get_special_times_adhoc(market_time: str) List[Any]
get_time(market_time: str, all_times: bool = False) Any
get_time_on(market_time: str, date: Any) time | None
property has_custom: bool
property has_discontinued: bool
holidays() CustomBusinessDay

Returns the complete CustomBusinessDay object of holidays that can be used in any Pandas function that take that input.

Returns:

CustomBusinessDay object of holidays

property interruptions: List[Any]

This needs to be a list with a tuple for each date that had an interruption. The tuple should have this layout:

(date, start_time, end_time[, start_time2, end_time2, …])

E.g.: [

(“2002-02-03”, (time(11), -1), time(11, 2)), (“2010-01-11”, time(11), (time(11, 1), 1)), (“2010-01-13”, time(9, 59), time(10), time(10, 29), time(10, 30)), (“2011-01-10”, time(11), time(11, 1))

]

The date needs to be a string in this format: ‘yyyy-mm-dd’. Times need to be two datetime.time objects for each interruption, indicating start and end.

Optionally these can be wrapped in a tuple, where the second element needs to be an integer indicating an offset.

On “2010-01-13” in the example, it is shown that there can be multiple interruptions in a day.

property interruptions_df: DataFrame

Will return a pd.DataFrame only containing interruptions.

is_custom(market_time: str) bool
is_different(col: Series, diff: Any = None) Series
is_discontinued(market_time: str) bool
is_open_now(schedule: DataFrame, include_close: bool = False, only_rth: bool = False) bool

To determine if the current local system time (converted to UTC) is an open time for the market

Parameters:
  • schedule – schedule DataFrame

  • include_close – if False then the function will return False if the current local system time is equal to the closing timestamp. If True then it will return True if the current local system time is equal to the closing timestamp. Use True if using bars and would like to include the last bar as a valid open date and time.

  • only_rth – whether to consider columns that are before market_open or after market_close

Returns:

True if the current local system time is a valid open date and time, False if not

late_opens(schedule: DataFrame) DataFrame

Get a DataFrame of the dates that are an late opens.

Parameters:

schedule – schedule DataFrame

Returns:

schedule DataFrame with rows that are late opens

property market_times: List[str]
abstract property name: str

Name of the market

Returns:

string name

open_at_time(schedule: Any, timestamp: Any, include_close: bool = False, only_rth: bool = False) bool

Determine if a given timestamp is during an open time for the market. If the timestamp is before the first open time or after the last close time of schedule, a ValueError will be raised.

Parameters:
  • schedule – schedule DataFrame

  • timestamp – the timestamp to check for. Assumed to be UTC, if it doesn’t include tz information.

  • include_close – if False then the timestamp that equals the closing timestamp will return False and not be considered a valid open date and time. If True then it will be considered valid and return True. Use True if using bars and would like to include the last bar as a valid open date and time. The close refers to the latest market_time available, which could be after market_close (e.g. ‘post’).

  • only_rth – whether to ignore columns that are before market_open or after market_close. If true, include_close will be referring to market_close.

Returns:

True if the timestamp is a valid open date and time, False if not

open_close_map: Any = {'break_end': True, 'break_start': False, 'market_close': False, 'market_open': True, 'post': False, 'pre': True}
property open_offset: int
Returns:

open offset

property open_time: time

Default open time for the market

Returns:

time

open_time_on(date: Any) time | None
property regular_holidays: AbstractHolidayCalendar | None
Returns:

pd.AbstractHolidayCalendar: a calendar containing the regular holidays for this calendar

regular_market_times: Any = {'market_close': ((None, datetime.time(23, 0)),), 'market_open': ((None, datetime.time(0, 0)),)}
remove_time(market_time: str) None

Removes the specified market time from regular_market_times and makes the necessary adjustments.

Parameters:

market_time – the market_time to remove

Returns:

None

schedule(start_date: Any, end_date: Any, tz: Any = 'UTC', start: Any = 'market_open', end: Any = 'market_close', force_special_times: Any = True, market_times: Any = None, interruptions: Any = False) DataFrame

Generates the schedule DataFrame. The resulting DataFrame will have all the valid business days as the index and columns for the requested market times. The columns can be determined either by setting a range (inclusive on both sides), using start and end, or by passing a list to `market_times’. A range of market_times is derived from a list of market_times that are available to the instance, which are sorted based on the current regular time. See examples/usage.ipynb for demonstrations.

All time zones are set to UTC by default. Setting the tz parameter will convert the columns to the desired timezone, such as ‘America/New_York’.

Parameters:
  • start_date – first date of the schedule

  • end_date – last date of the schedule

  • tz – timezone that the columns of the returned schedule are in, default: “UTC”

  • start – the first market_time to include as a column, default: “market_open”

  • end – the last market_time to include as a column, default: “market_close”

  • force_special_times

    how to handle special times. True: overwrite regular times of the column itself, conform other columns to special times of

    market_open/market_close if those are requested.

    False: only overwrite regular times of the column itself, leave others alone None: completely ignore special times

  • market_times – alternative to start/end, list of market_times that are in self.regular_market_times

  • interruptions – bool, whether to add interruptions to the schedule, default: False These will be added as columns to the right of the DataFrame. Any interruption on a day between start_date and end_date will be included, regardless of the market_times requested. Also, force_special_times does not take these into consideration.

Returns:

schedule DataFrame

schedule_from_days(days: DatetimeIndex, tz: str = 'UTC', start: str = 'market_open', end: str = 'market_close', force_special_times: Any = True, market_times: Any = None, interruptions: bool = False) DataFrame

Generates a schedule DataFrame for the days provided. The days are assumed to be valid trading days.

The columns can be determined either by setting a range (inclusive on both sides), using start and end, or by passing a list to `market_times’. A range of market_times is derived from a list of market_times that are available to the instance, which are sorted based on the current regular time. See examples/usage.ipynb for demonstrations.

All time zones are set to UTC by default. Setting the tz parameter will convert the columns to the desired timezone, such as ‘America/New_York’.

Parameters:
  • days – pd.DatetimeIndex of all the desired days in ascending order. This function does not double check that these are valid trading days, it is assumed they are. It is intended that this parameter is generated by either the .valid_days() or .date_range_htf() methods. Time & Timezone Information is ignored.

  • tz – timezone that the columns of the returned schedule are in, default: “UTC”

  • start – the first market_time to include as a column, default: “market_open”

  • end – the last market_time to include as a column, default: “market_close”

  • force_special_times

    how to handle special times. True: overwrite regular times of the column itself, conform other columns to special times of

    market_open/market_close if those are requested, and preserve any explicitly requested special time for its own column.

    False: only overwrite regular times of the column itself, leave others alone None: completely ignore special times

  • market_times – alternative to start/end, list of market_times that are in self.regular_market_times

  • interruptions – bool, whether to add interruptions to the schedule, default: False These will be added as columns to the right of the DataFrame. Any interruption on a day between start_date and end_date will be included, regardless of the market_times requested. Also, force_special_times does not take these into consideration.

Returns:

schedule DataFrame

property sources: tuple[Source, ...]

Source references for this calendar’s data.

Returns a tuple of Source objects containing information about where the calendar’s trading hours, holidays, and other data originated from.

Returns:

tuple of Source namedtuples with fields (name, url, last_verified, covers, notes)

property special_closes: List[Any]

A list of special close times and corresponding HolidayCalendars.

Returns:

List of (time, AbstractHolidayCalendar) tuples

property special_closes_adhoc: List[Any]
Returns:

List of (time, DatetimeIndex) tuples that represent special closes that cannot be codified into rules.

special_dates(market_time: str, start_date: Any, end_date: Any, filter_holidays: bool = True) Series

Calculate a datetimeindex that only contains the specail times of the requested market time.

Parameters:
  • market_time – market_time reference

  • start_date – first possible date of the index

  • end_date – last possible date of the index

  • filter_holidays – will filter days by self.valid_days, which can be useful when debugging

Returns:

schedule DatetimeIndex

property special_market_close: List[Any]

A list of special close times and corresponding HolidayCalendars.

Returns:

List of (time, AbstractHolidayCalendar) tuples

property special_market_close_adhoc: List[Any]
Returns:

List of (time, DatetimeIndex) tuples that represent special closes that cannot be codified into rules.

property special_market_open: List[Any]

A list of special open times and corresponding AbstractHolidayCalendar.

Returns:

List of (time, AbstractHolidayCalendar) tuples

property special_market_open_adhoc: List[Any]
Returns:

List of (time, DatetimeIndex) tuples that represent special opens that cannot be codified into rules.

property special_opens: List[Any]

A list of special open times and corresponding AbstractHolidayCalendar.

Returns:

List of (time, AbstractHolidayCalendar) tuples

property special_opens_adhoc: List[Any]
Returns:

List of (time, DatetimeIndex) tuples that represent special opens that cannot be codified into rules.

abstract property tz: Any

Time zone for the market.

Returns:

timezone

valid_days(start_date: Any, end_date: Any, tz: Any = 'UTC') DatetimeIndex

Get a DatetimeIndex of valid open business days.

Parameters:
  • start_date – start date

  • end_date – end date

  • tz – time zone in either string or pytz.timezone

Returns:

DatetimeIndex of valid business days

property weekmask: str
class pandas_market_calendars.market_calendar.MarketCalendarMeta(name, bases, namespace, /, **kwargs)

Bases: ABCMeta, RegisteryMeta

pandas_market_calendars.trading_calendars_mirror module

Module contents

class pandas_market_calendars.MarketCalendar(open_time: time | None = None, close_time: time | None = None)

Bases: object

An MarketCalendar represents the timing information of a single market or exchange. Unless otherwise noted all times are in UTC and use Pandas data structures.

Parameters:
  • open_time – Market open time override as datetime.time object. If None then default is used.

  • close_time – Market close time override as datetime.time object. If None then default is used.

add_time(market_time: str, times: Any, opens: Any = <class 'pandas_market_calendars.market_calendar.DEFAULT'>) None

Adds the specified market time to regular_market_times and makes the necessary adjustments.

Parameters:
  • market_time – the market_time to add

  • times – the time information

  • opens – see .change_time docstring

Returns:

None

property adhoc_holidays: List[Any]
Returns:

list of ad-hoc holidays

property break_end: time | None

Break time end. If None then there is no break

Returns:

time or None

break_end_on(date: Any) time | None
property break_start: time | None

Break time start. If None then there is no break

Returns:

time or None

break_start_on(date: Any) time | None
classmethod calendar_names() List[str]

All Market Calendar names and aliases that can be used in “factory” :return: list(str)

change_time(market_time: str, times: Any, opens: Any = <class 'pandas_market_calendars.market_calendar.DEFAULT'>) None

Changes the specified market time in regular_market_times and makes the necessary adjustments.

Parameters:
  • market_time – the market_time to change

  • times – new time information

  • opens

    whether the market_time is a time that closes or opens the market this is only needed if the market_time should be respected by .open_at_time True: opens False: closes None: consider it neither opening nor closing, don’t add to open_close_map (ignore in .open_at_time) DEFAULT: same as None, unless the market_time is in self.__class__.open_close_map. Then it will take

    the default value as defined by the class.

Returns:

None

clean_dates(start_date: Any, end_date: Any) Tuple[Timestamp, Timestamp]

Strips the inputs of time and time zone information

Parameters:
  • start_date – start date

  • end_date – end date

Returns:

(start_date, end_date) with just date, no time and no time zone

property close_offset: int
Returns:

close offset

property close_time: time

Default close time for the market

Returns:

time

close_time_on(date: Any) time | None
date_range_htf(frequency: str | Timedelta | int | float, start: str | Timestamp | int | float | None = None, end: str | Timestamp | int | float | None = None, periods: int | None = None, closed: Literal['left', 'right'] | None = 'right', *, day_anchor: Literal['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] = 'SUN', month_anchor: Literal['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] = 'JAN') DatetimeIndex

Returns a Normalized DatetimeIndex from the start-date to End-Date for Time periods of 1D and Higher.

PARAMETERS:

Parameters:
  • frequency

    String, Int/float (POSIX seconds) or pd.Timedelta of the desired frequency. :Must be Greater than ‘1D’ and an integer multiple of the base frequency (D, W, M, Q, or Y) :Important Note: Ints/Floats & Timedeltas are always considered as ‘Open Business Days’,

    ’2D’ == Every Other Buisness Day, ‘3D’ == Every 3rd B.Day, ‘7D’ == Every 7th B.Day

    :Higher periods (passed as strings) align to the beginning or end of the relevant period :i.e. ‘1W’ == First/[Last] Trading Day of each Week, ‘1Q’ == First/[Last] Day of every Quarter

  • start – String, Int/float (POSIX seconds) or pd.Timestamp of the desired start time. :The Time & Timezone information is ignored. Only the Normalized Day is considered.

  • end – String, Int/float (POSIX seconds) or pd.Timestamp of the desired start time. :The Time & Timezone information is ignored. Only the Normalized Day is considered.

  • periods – Optional Integer number of periods to return. If a Period count, Start time, and End time are given the period count is ignored.

  • closed – Literal[‘left’, ‘right’]. Method used to close each range. :Left: First open trading day of the Session is returned (e.g. First Open Day of The Month) :right: Last open trading day of the Session is returned (e.g. Last Open Day of The Month) :Note, This has no effect when the desired frequency is a number of days.

  • day_anchor

    Day to Anchor the start of the Weekly timeframes to. Default ‘SUN’. : To get the First/Last Days of the trading Week then the Anchor needs to be on a day the relevant

    market is closed.

    : This can be set so that a specific day each week is returned. : freq=’1W’ & day_anchor=’WED’ Will return Every ‘WED’ when the market is open, and nearest day

    to the left or right (based on ‘closed’) when the market is closed.

    Options: [“SUN”, “MON”, “TUE”, “WED”, “THU”, “FRI”, “SAT”]

  • month_anchor – Month to Anchor the start of the year to for Quarter and yearly timeframes. : Default ‘JAN’ for Calendar Quarters/Years. Can be set to ‘JUL’ to return Fiscal Years Options: [“JAN”, “FEB”, “MAR”, “APR”, “MAY”, “JUN”, “JUL”, “AUG”, “SEP”, “OCT”, “NOV”, “DEC”]

days_at_time(days: Any, market_time: str | time, day_offset: int = 0) Series

Create an index of days at time t, interpreted in timezone tz. The returned index is localized to UTC.

In the example below, the times switch from 13:45 to 12:45 UTC because March 13th is the daylight savings transition for US/Eastern. All the times are still 8:45 when interpreted in US/Eastern.

>>> import pandas as pd
... import datetime
... import pprint
>>> dts = pd.date_range("2016-03-12", "2016-03-14")
>>> dts_at_845 = days_at_time(dts, datetime.time(8, 45), "US/Eastern")
>>> pprint.pprint([str(dt) for dt in dts_at_845])
['2016-03-12 13:45:00+00:00',
 '2016-03-13 12:45:00+00:00',
 '2016-03-14 12:45:00+00:00']
Parameters:
  • days – DatetimeIndex An index of dates (represented as midnight).

  • market_time – datetime.time The time to apply as an offset to each day in days.

  • day_offset – int The number of days we want to offset @days by

Returns:

pd.Series of date with the time requested.

discontinued_market_times: ProtectedDict
early_closes(schedule: DataFrame) DataFrame

Get a DataFrame of the dates that are an early close.

Parameters:

schedule – schedule DataFrame

Returns:

schedule DataFrame with rows that are early closes

classmethod factory(name: str, *args: Any, **kwargs: Any) Any
Parameters:
  • cls(RegisteryMeta) – registration meta class

  • name(str) – name of class that needs to be instantiated

  • args(Optional(tuple)) – instance positional arguments

  • kwargs(Optional(dict)) – instance named arguments

Returns:

class instance

property full_name: str

Full name of the market

Returns:

string name

get_offset(market_time: str) int
get_special_times(market_time: str) List[Any]
get_special_times_adhoc(market_time: str) List[Any]
get_time(market_time: str, all_times: bool = False) Any
get_time_on(market_time: str, date: Any) time | None
property has_custom: bool
property has_discontinued: bool
holidays() CustomBusinessDay

Returns the complete CustomBusinessDay object of holidays that can be used in any Pandas function that take that input.

Returns:

CustomBusinessDay object of holidays

property interruptions: List[Any]

This needs to be a list with a tuple for each date that had an interruption. The tuple should have this layout:

(date, start_time, end_time[, start_time2, end_time2, …])

E.g.: [

(“2002-02-03”, (time(11), -1), time(11, 2)), (“2010-01-11”, time(11), (time(11, 1), 1)), (“2010-01-13”, time(9, 59), time(10), time(10, 29), time(10, 30)), (“2011-01-10”, time(11), time(11, 1))

]

The date needs to be a string in this format: ‘yyyy-mm-dd’. Times need to be two datetime.time objects for each interruption, indicating start and end.

Optionally these can be wrapped in a tuple, where the second element needs to be an integer indicating an offset.

On “2010-01-13” in the example, it is shown that there can be multiple interruptions in a day.

property interruptions_df: DataFrame

Will return a pd.DataFrame only containing interruptions.

is_custom(market_time: str) bool
is_different(col: Series, diff: Any = None) Series
is_discontinued(market_time: str) bool
is_open_now(schedule: DataFrame, include_close: bool = False, only_rth: bool = False) bool

To determine if the current local system time (converted to UTC) is an open time for the market

Parameters:
  • schedule – schedule DataFrame

  • include_close – if False then the function will return False if the current local system time is equal to the closing timestamp. If True then it will return True if the current local system time is equal to the closing timestamp. Use True if using bars and would like to include the last bar as a valid open date and time.

  • only_rth – whether to consider columns that are before market_open or after market_close

Returns:

True if the current local system time is a valid open date and time, False if not

late_opens(schedule: DataFrame) DataFrame

Get a DataFrame of the dates that are an late opens.

Parameters:

schedule – schedule DataFrame

Returns:

schedule DataFrame with rows that are late opens

property market_times: List[str]
abstract property name: str

Name of the market

Returns:

string name

open_at_time(schedule: Any, timestamp: Any, include_close: bool = False, only_rth: bool = False) bool

Determine if a given timestamp is during an open time for the market. If the timestamp is before the first open time or after the last close time of schedule, a ValueError will be raised.

Parameters:
  • schedule – schedule DataFrame

  • timestamp – the timestamp to check for. Assumed to be UTC, if it doesn’t include tz information.

  • include_close – if False then the timestamp that equals the closing timestamp will return False and not be considered a valid open date and time. If True then it will be considered valid and return True. Use True if using bars and would like to include the last bar as a valid open date and time. The close refers to the latest market_time available, which could be after market_close (e.g. ‘post’).

  • only_rth – whether to ignore columns that are before market_open or after market_close. If true, include_close will be referring to market_close.

Returns:

True if the timestamp is a valid open date and time, False if not

open_close_map: Any = {'break_end': True, 'break_start': False, 'market_close': False, 'market_open': True, 'post': False, 'pre': True}
property open_offset: int
Returns:

open offset

property open_time: time

Default open time for the market

Returns:

time

open_time_on(date: Any) time | None
property regular_holidays: AbstractHolidayCalendar | None
Returns:

pd.AbstractHolidayCalendar: a calendar containing the regular holidays for this calendar

regular_market_times: Any = {'market_close': ((None, datetime.time(23, 0)),), 'market_open': ((None, datetime.time(0, 0)),)}
remove_time(market_time: str) None

Removes the specified market time from regular_market_times and makes the necessary adjustments.

Parameters:

market_time – the market_time to remove

Returns:

None

schedule(start_date: Any, end_date: Any, tz: Any = 'UTC', start: Any = 'market_open', end: Any = 'market_close', force_special_times: Any = True, market_times: Any = None, interruptions: Any = False) DataFrame

Generates the schedule DataFrame. The resulting DataFrame will have all the valid business days as the index and columns for the requested market times. The columns can be determined either by setting a range (inclusive on both sides), using start and end, or by passing a list to `market_times’. A range of market_times is derived from a list of market_times that are available to the instance, which are sorted based on the current regular time. See examples/usage.ipynb for demonstrations.

All time zones are set to UTC by default. Setting the tz parameter will convert the columns to the desired timezone, such as ‘America/New_York’.

Parameters:
  • start_date – first date of the schedule

  • end_date – last date of the schedule

  • tz – timezone that the columns of the returned schedule are in, default: “UTC”

  • start – the first market_time to include as a column, default: “market_open”

  • end – the last market_time to include as a column, default: “market_close”

  • force_special_times

    how to handle special times. True: overwrite regular times of the column itself, conform other columns to special times of

    market_open/market_close if those are requested.

    False: only overwrite regular times of the column itself, leave others alone None: completely ignore special times

  • market_times – alternative to start/end, list of market_times that are in self.regular_market_times

  • interruptions – bool, whether to add interruptions to the schedule, default: False These will be added as columns to the right of the DataFrame. Any interruption on a day between start_date and end_date will be included, regardless of the market_times requested. Also, force_special_times does not take these into consideration.

Returns:

schedule DataFrame

schedule_from_days(days: DatetimeIndex, tz: str = 'UTC', start: str = 'market_open', end: str = 'market_close', force_special_times: Any = True, market_times: Any = None, interruptions: bool = False) DataFrame

Generates a schedule DataFrame for the days provided. The days are assumed to be valid trading days.

The columns can be determined either by setting a range (inclusive on both sides), using start and end, or by passing a list to `market_times’. A range of market_times is derived from a list of market_times that are available to the instance, which are sorted based on the current regular time. See examples/usage.ipynb for demonstrations.

All time zones are set to UTC by default. Setting the tz parameter will convert the columns to the desired timezone, such as ‘America/New_York’.

Parameters:
  • days – pd.DatetimeIndex of all the desired days in ascending order. This function does not double check that these are valid trading days, it is assumed they are. It is intended that this parameter is generated by either the .valid_days() or .date_range_htf() methods. Time & Timezone Information is ignored.

  • tz – timezone that the columns of the returned schedule are in, default: “UTC”

  • start – the first market_time to include as a column, default: “market_open”

  • end – the last market_time to include as a column, default: “market_close”

  • force_special_times

    how to handle special times. True: overwrite regular times of the column itself, conform other columns to special times of

    market_open/market_close if those are requested, and preserve any explicitly requested special time for its own column.

    False: only overwrite regular times of the column itself, leave others alone None: completely ignore special times

  • market_times – alternative to start/end, list of market_times that are in self.regular_market_times

  • interruptions – bool, whether to add interruptions to the schedule, default: False These will be added as columns to the right of the DataFrame. Any interruption on a day between start_date and end_date will be included, regardless of the market_times requested. Also, force_special_times does not take these into consideration.

Returns:

schedule DataFrame

property sources: tuple[Source, ...]

Source references for this calendar’s data.

Returns a tuple of Source objects containing information about where the calendar’s trading hours, holidays, and other data originated from.

Returns:

tuple of Source namedtuples with fields (name, url, last_verified, covers, notes)

property special_closes: List[Any]

A list of special close times and corresponding HolidayCalendars.

Returns:

List of (time, AbstractHolidayCalendar) tuples

property special_closes_adhoc: List[Any]
Returns:

List of (time, DatetimeIndex) tuples that represent special closes that cannot be codified into rules.

special_dates(market_time: str, start_date: Any, end_date: Any, filter_holidays: bool = True) Series

Calculate a datetimeindex that only contains the specail times of the requested market time.

Parameters:
  • market_time – market_time reference

  • start_date – first possible date of the index

  • end_date – last possible date of the index

  • filter_holidays – will filter days by self.valid_days, which can be useful when debugging

Returns:

schedule DatetimeIndex

property special_market_close: List[Any]

A list of special close times and corresponding HolidayCalendars.

Returns:

List of (time, AbstractHolidayCalendar) tuples

property special_market_close_adhoc: List[Any]
Returns:

List of (time, DatetimeIndex) tuples that represent special closes that cannot be codified into rules.

property special_market_open: List[Any]

A list of special open times and corresponding AbstractHolidayCalendar.

Returns:

List of (time, AbstractHolidayCalendar) tuples

property special_market_open_adhoc: List[Any]
Returns:

List of (time, DatetimeIndex) tuples that represent special opens that cannot be codified into rules.

property special_opens: List[Any]

A list of special open times and corresponding AbstractHolidayCalendar.

Returns:

List of (time, AbstractHolidayCalendar) tuples

property special_opens_adhoc: List[Any]
Returns:

List of (time, DatetimeIndex) tuples that represent special opens that cannot be codified into rules.

abstract property tz: Any

Time zone for the market.

Returns:

timezone

valid_days(start_date: Any, end_date: Any, tz: Any = 'UTC') DatetimeIndex

Get a DatetimeIndex of valid open business days.

Parameters:
  • start_date – start date

  • end_date – end date

  • tz – time zone in either string or pytz.timezone

Returns:

DatetimeIndex of valid business days

property weekmask: str
pandas_market_calendars.convert_freq(index: DatetimeIndex, frequency: str) pd.Index[Any]

Converts a DateTimeIndex to a new lower frequency

Parameters:
  • index – DateTimeIndex

  • frequency – frequency string

Returns:

DateTimeIndex

pandas_market_calendars.date_range(schedule: DataFrame, frequency: str | Timedelta | int | float, closed: Literal['left', 'right', 'both'] | None = 'right', force_close: bool | None = True, session: Literal['pre', 'post', 'RTH', 'pre_break', 'post_break', 'ETH', 'break', 'closed', 'closed_masked'] | Iterable[Literal['pre', 'post', 'RTH', 'pre_break', 'post_break', 'ETH', 'break', 'closed', 'closed_masked']] | None = None, merge_adjacent: bool = True, start: str | Timestamp | int | float | None = None, end: str | Timestamp | int | float | None = None, periods: int | None = None) DatetimeIndex

Interpolates a Market’s Schedule at the desired frequency and returns the result as a DatetimeIndex. This function is only valid for periods less than 1 Day, for longer periods use date_range_htf().

Note: The slowest part of this function is by far generating the necessary schedule (which in turn is limited by pandas’ date_range() function). If speed is a concern, store and update the schedule as needed instead of generating it every time.

WARNINGS SYSTEM:

*There are multiple edge-case warnings that are thrown by this function. See the Docstrings of each warning for more info. (DateRangeWarning, InsufficientScheduleWarning, MissingSessionWarning, OverlappingSessionWarning, DisappearingSessionWarning)

*The thrown warnings can be ignored or escalated into catchable errors by using the filter_date_range_warnings() function.

parse_missing_session_warning() & parse_insufficient_schedule_warning() exist to easily process the warnings those warnings if they are escalated into errors.

PARAMETERS:

Parameters:
  • schedule – Schedule of a calendar which includes all the columns necessary for the desired sessions.

  • frequency – String, Int/float (seconds) or pd.Timedelta that represents the desired interval of the date_range. Intervals larger than 1D are not supported.

  • closed – the way the intervals are labeled ‘right’: use the end of the interval ‘left’: use the start of the interval None / ‘both’: use the end of the interval but include the start of the first interval

  • force_close – How the last value of a trading session is handled True: guarantee that the close of the trading session is the last value False: guarantee that there is no value greater than the close of the trading session None: leave the last value as it is calculated based on the closed parameter

  • session

    A str representing a single session or an Iterable of the following Sessions. RTH: The Default Option. This is [Market_open, Market_close], if the schedule includes a

    break then the break is excluded from the returned datetime index.

    ETH: [pre, market_open] & [market_close, post] pre: [pre, market_open] post: [market_close, post] break: [break_start, break_end] pre_break: [market_open, break_start] post_break: [break_end, market_close] closed: [market_close, market_open (of the next day)] If ETH market times are given then

    this will be [post, pre (of the next day)] instead. The last session will end at Midnight of the timezone the schedule is given in.

    closed_masked: Same as closed, but Weekends & Holidays are ignored. Instead, the Datetime

    index stops at Midnight on the trading day before the break and resumes at midnight prior to the next trading day. **Note: This is Midnight of the Timezone the schedule is given in, not Midnight of the exchange’s tz since the exchange’s tz is not known.

  • merge_adjacent

    Bool representing if adjacent sessions should be merged into a single session. For Example, NYSE w/ session={‘RTH’, ‘ETH’}, frequency=2h, closed=left, force_close=False merge_adjacent == True => [pre, post]

    >>> ['2020-01-02 04:00:00', '2020-01-02 06:00:00',
         '2020-01-02 08:00:00', '2020-01-02 10:00:00',
         '2020-01-02 12:00:00', '2020-01-02 14:00:00',
         '2020-01-02 16:00:00', '2020-01-02 18:00:00']
    
    merge_adjacent == False => [pre, market_open] & [market_open, market_close] & [market_close, post]
    >>> ['2020-01-02 04:00:00', '2020-01-02 06:00:00',
         '2020-01-02 08:00:00', '2020-01-02 09:30:00',
         '2020-01-02 11:30:00', '2020-01-02 13:30:00',
         '2020-01-02 15:30:00', '2020-01-02 16:00:00',
         '2020-01-02 18:00:00']
    

    merge_adjacent=False re-aligns the timestamps to the session, but this results in the difference between timestamps not always equaling the desired frequency.

  • start

    Optional [String, Int/float (POSIX seconds) or pd.Timestamp] of the desired start time. :If left as None then the start-time of the the Schedule is used. :If no TZ info is given it will be interpreted in the same timezone as the first column of the schedule :Start can be a Day and Time, but the returned index will still be aligned to the underlying schedule. e.g. Session = [9:30am, 12pm], frequency=7min, start=9:45am. Underlying session

    = [9:30, 9:37, 9:44, 9:51, …] => returned DatetimeIndex = [9:51, …]

  • end – Optional [String, Int/float (POSIX seconds) or pd.Timestamp] of the desired end time. :If left as None then the end-time of the the Schedule is used. :If no TZ info is given it will be interpreted in the same timezone as the first column **Note: The time given is an absolute value. i.e. end=”2020-01-01” == “2020-01-01 00:00” returning times prior to Midnight of “2019-12-31”, not to the EOD of “2020-01-01”

  • periods

    Optional Integer number of periods to return. If a Period count, Start time, and End time are given the period count is ignored. None: Period count is ignored. Returned index is all periods in [Start, End] Int: # of periods to return. By default, this is the first N periods following the start.

    If an end time is given then this is the N periods prior to the End Time (inclusive).

    CAVEAT: When Force_close == False & closed == ‘right’/’both’ the number of periods returned

    may be less than the parameter given.

Returns:

pd.DatetimeIndex of datetime64[ns, TZ-Aware]

pandas_market_calendars.get_calendar(name: str, open_time: time | None = None, close_time: time | None = None) MarketCalendar

Retrieves an instance of an MarketCalendar whose name is given.

Parameters:
  • name – The name of the MarketCalendar to be retrieved.

  • open_time – Market open time override as datetime.time object. If None then default is used.

  • close_time – Market close time override as datetime.time object. If None then default is used.

Returns:

MarketCalendar of the desired calendar.

pandas_market_calendars.get_calendar_names() list[str]

All Market Calendar names and aliases that can be used in “factory” :return: list(str)

pandas_market_calendars.mark_session(schedule: DataFrame, timestamps: DatetimeIndex, label_map: Dict[str, Any] | None = None, *, closed: Literal['left', 'right'] = 'right') Series

Return a Series that denotes the trading session of each timestamp in a DatetimeIndex. The returned Series’s Index is the provided Datetime Index, the Series’s values are the timestamps’ corresponding session.

PARAMETERS:

Parameters:
  • schedule – The market schedule to check the timestamps against. This Schedule must include all of the trading days that are in the provided DatetimeIndex of timestamps. Note: The columns need to be sorted into ascending order, if not, then an error will be raised saying the bins must be in ascending order.

  • timestamps – A DatetimeIndex of Timestamps to check. Must be sorted in ascending order.

  • label_map

    Optional mapping of Dict[str, Any] to change the values returned in the series. The keys of the given mapping should match the keys of the default dict, but the values can be anything. A subset of mappings may also be provided, e.g. {‘closed’:-1} will only change the label of the ‘closed’ session. All others will remain the default label.

    >>> Default Mapping == {
        "pre": "pre",
        "rth_pre_break": "rth",     # When the Schedule has a break
        "rth": "rth",               # When the Schedule doesn't have a break
        "break": "break",           # When the Schedule has a break
        "rth_post_break": "rth",    # When the Schedule has a break
        "post": "post",
        "closed": "closed",
    }
    

  • closed – Which side of each interval should be closed (inclusive) left: == [start, end) right: == (start, end]

pandas_market_calendars.merge_schedules(schedules: List[DataFrame], how: Literal['outer', 'inner'] = 'outer') DataFrame

Given a list of schedules will return a merged schedule. The merge method (how) will either return the superset of any datetime when any schedule is open (outer) or only the datetime where all markets are open (inner)

CAVEATS:
  • This does not work for schedules with breaks, the break information will be lost.

  • Only “market_open” and “market_close” are considered, other market times are not yet supported.

Parameters:
  • schedules – list of schedules

  • how – outer or inner

Returns:

schedule DataFrame