### Set up Development Environment and Pre-commit Hook Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/CONTRIBUTING.md This sequence of commands sets up a virtual environment, installs the project with development dependencies, and installs the pre-commit hook for code formatting. ```bash python -m venv .venv . .venv/bin/activate python -m pip install --upgrade pip pip install -e .[dev] pre-commit install ``` -------------------------------- ### Get pandas_market_calendars Version Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/CONTRIBUTING.md Use this command to retrieve the installed version of the pandas_market_calendars library. ```python python -c "import pandas_market_calendars; print(pandas_market_calendars.__version__)" ``` -------------------------------- ### Setup new exchange calendar Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Initializes a calendar for a specific exchange, such as the New York Stock Exchange (NYSE). ```python nyse = mcal.get_calendar("NYSE") ``` -------------------------------- ### Get First Trading Day of Next 10 Fiscal Years (NYSE) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Demonstrates how to find the first trading day of the next 10 fiscal years, anchored to July, using NYSE calendar. Requires specifying the start date and number of periods. ```python nyse.date_range_htf("Y", start="2017-01-01", periods=10, closed="left", month_anchor="JUL") ``` -------------------------------- ### Docstring Example with Sphinx/reStructuredText Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/AGENTS.md Illustrates the required format for docstrings using Sphinx/reStructuredText field lists. Includes parameter, return, and raises specifications. ```python def add(a: int, b: int) -> int: """ Add two integers. :param a: The first addend. :param b: The second addend. :return: The sum of a and b. """ return a + b ``` -------------------------------- ### Get Exchange Calendar Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Instantiate a calendar for a specific exchange like NYSE. This is the first step to accessing market data. ```python import sys sys.path.append("../") from datetime import time import pandas as pd import pandas_market_calendars as mcal ``` ```python nyse = mcal.get_calendar('NYSE') ``` -------------------------------- ### Get All Market Open Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieves all recorded market open times for a calendar. This can be used to get a historical overview of opening times. ```python nyse["market_open", "all"] # gets all times ``` ```default ((None, datetime.time(10, 0)), ('1985-01-01', datetime.time(9, 30))) ``` -------------------------------- ### Get Trading Schedule with Pre and Post-Market Times (NYSE) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves a trading schedule that includes pre-market and post-market times in addition to regular market open and close. The 'start' and 'end' parameters control the inclusion of these extended hours. ```python # including pre and post-market extended = nyse.schedule(start_date="2012-07-01", end_date="2012-07-10", start="pre", end="post") extended ``` -------------------------------- ### Generate and Mark Trading Sessions (Default) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates a DatetimeIndex with a 2-hour frequency and marks each timestamp with its corresponding trading session (pre, rth, post). This example uses default settings for session merging. ```python dt = mcal.date_range( nyse_schedule, "2h", start="2012-07-05 04:00:00", periods=10, session={"RTH", "ETH"}, closed="left", force_close=None, ) mcal.mark_session(nyse_schedule, dt, closed="left") ``` -------------------------------- ### Generate Date Range with Custom Start Timestamp Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates a date range using a specified frequency and a custom start timestamp with timezone information. The returned dates align with the underlying session and frequency. ```python mcal.date_range( nyse_schedule, frequency="1h", start="2012-07-02 13:34:39-04:00", periods=8, closed="left", force_close=False ) ``` -------------------------------- ### Get Market Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Generate a detailed schedule of market open and close times for a given date range. This includes regular trading days. ```python schedule = nyse.schedule(start_date='2016-12-30', end_date='2017-01-10') schedule ``` -------------------------------- ### Generate business days using date_range_htf with start date and periods Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates a specified number of open business days starting from a given date. ```python # However, it can be used in a similar manner to pandas.date_range() # Request a number of open days from a given start date nyse.date_range_htf("1D", start="2017-01-01", periods=4) ``` -------------------------------- ### Get Python Version Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/CONTRIBUTING.md Use this command to check your current Python version. ```bash python --version ``` -------------------------------- ### Get Schedule with Interruptions Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generate a market schedule for a given date range, including interruptions by setting `interruptions=True`. ```python sched = cal.schedule("2010-01-09", "2010-01-15", interruptions=True) sched ``` -------------------------------- ### Select Specific Trading Sessions with date_range Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Use the 'session' argument to specify which trading sessions to include in the date range. This example includes Extended Trading Hours (ETH). ```python mcal.date_range(nyse_schedule, frequency="1h", session="ETH", closed="left", force_close=None) ``` -------------------------------- ### Generate and Mark Trading Sessions (Merge Adjacent False) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates a DatetimeIndex with a 2-hour frequency, similar to the previous example, but with `merge_adjacent=False`. This can lead to more granular session marking, distinguishing between different parts of the trading day more precisely. ```python # This makes it much easier to identify nuances in date_range() results like the # one described above in the date_range(merge_adjacent=True/False) discussion dt = mcal.date_range( nyse_schedule, "2h", start="2012-07-05 04:00:00", periods=10, merge_adjacent=False, session={"RTH", "ETH"}, closed="left", force_close=None, ) mcal.mark_session(nyse_schedule, dt, closed="left") ``` -------------------------------- ### Generate Schedule with Custom Order Acceptance Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generate a trading schedule for a specific date range using a custom exchange calendar, specifying 'order_acceptance' as the start time. This demonstrates how the custom 'order_acceptance' time and ad-hoc special cases are reflected in the schedule. ```python schedule = options.schedule("2000-12-22", "2000-12-28", start="order_acceptance") schedule ``` -------------------------------- ### Greater Than or Equal Schedule Difference Check Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb This example demonstrates using `is_different` with `pd.Series.ge` to find market entries where the 'order_acceptance' time is greater than or equal to the regular market times. ```python schedule[options.is_different(schedule["order_acceptance"], pd.Series.ge)] ``` -------------------------------- ### Get Extended Market Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Fetch market schedule including pre and post-market times. This is useful for understanding the full trading day duration. ```python extended = nyse.schedule(start_date='2012-07-01', end_date='2012-07-10', start="pre", end="post") extended ``` -------------------------------- ### Generate Schedule for Custom Calendar Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Generate a market schedule using a custom calendar, specifying the date range and the starting market time. This demonstrates how custom regular and special times are applied. ```python schedule = options.schedule("2000-12-22", "2000-12-28", start= "order_acceptance") schedule ``` -------------------------------- ### Change Market Open Time Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Use `change_time` to replace an existing market time. This example sets the NYSE market open to 10:30 AM. ```python cal = mcal.get_calendar("NYSE") cal.change_time("market_open", time(10,30)) print('open, close: %s, %s' % (cal.open_time, cal.close_time)) print("\nThe 'market_open' information is entirely replaced:\n", cal.regular_market_times) ``` -------------------------------- ### Get Market Schedule with Early Closes Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieve the market schedule, specifically showing days with early closing times. This is useful for understanding trading variations. ```python # with early closes early = nyse.schedule(start_date='2012-07-01', end_date='2012-07-10') early ``` -------------------------------- ### Inspect Generated Schedules Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/AGENTS.md Use `calendar.schedule(start, end)` to inspect generated schedules. This is useful for verifying the output of calendar operations. ```python calendar.schedule(start, end) ``` -------------------------------- ### Get Early Closes Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Identify and display early closing times from a given market schedule. This is useful for days with shortened trading hours. ```python nyse.early_closes(schedule=early) ``` -------------------------------- ### Get XKRX Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the trading schedule for the XKRX market for a specified date range. Note the potential UserWarning about discontinued market times. ```python xkrx.schedule("2020-01-01", "2020-01-05") ``` -------------------------------- ### Get Trading Schedule with Early Closes (NYSE) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Fetches the trading schedule for a date range, including days with early closes. Note the adjusted market_close times for specific dates. ```python # with early closes early = nyse.schedule(start_date="2012-07-01", end_date="2012-07-10") early ``` -------------------------------- ### Get the first trading day of every month Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Fetches the first trading day of each month within a given range, using the 'left' closed interval. ```python # The First Trading Day of every Month in the range nyse.date_range_htf("1M", start="2017-01-01", end="2018-01-01", closed="left") ``` -------------------------------- ### Get Current Pre and Post Market Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Access the current pre-market (`pre`) and post-market (`post`) times using the `get_time` method. These represent the standard times for trading sessions outside regular hours. ```python nyse.get_time("post"), nyse.get_time("pre") ``` -------------------------------- ### Get Trading Schedule with Specific Market Times (NYSE) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Fetches a trading schedule for a specified date range, including only the 'post' and 'market_open' times in the order specified. Note that times are not adjusted to special opens/closes if market_open/market_close are not requested. ```python # specific market times # CAVEAT: Looking at 2012-07-03, you can see that times will NOT be adjusted to special_opens/sepcial_closes # if market_open/market_close are not requested specific = nyse.schedule( start_date="2012-07-01", end_date="2012-07-10", market_times=["post", "market_open"]) # this order will be kept specific ``` -------------------------------- ### Get Current Market Open Time Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieves the current market open time for a given calendar. This is useful for checking the immediate opening time. ```python nyse["market_open"] # gets the current time ``` ```default datetime.time(9, 30, tzinfo=) ``` -------------------------------- ### Get Schedule with Trading Breaks Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieves a market schedule that includes trading breaks. This is useful for markets with intra-day closures, such as CME Equity Futures. ```python cme = mcal.get_calendar('CME_Equity') schedule = cme.schedule('2020-01-01', '2020-01-04') schedule ``` -------------------------------- ### Get First and Last Trading Day of Each Quarter Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates the first and last trading days for each quarter of a given year using date_range_htf and schedule_from_days. ```python dates_end = nyse.date_range_htf("Q", start="2017-01-01", periods=4) dates_start = nyse.date_range_htf("Q", start="2017-01-01", periods=4, closed="left") nyse.schedule_from_days(dates_start.union(dates_end).sort_values(), market_times="all", tz=nyse.tz) ``` -------------------------------- ### Generate Hourly Date Range (Left Closed) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates a DatetimeIndex with hourly frequency, starting from the market open time for each trading day. Uses 'closed="left"' and 'force_close=False'. ```python mcal.date_range(nyse_schedule, frequency="1h", closed="left", force_close=False) ``` -------------------------------- ### Get NYSE Schedule with All Market Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the full trading schedule for the NYSE, including pre-market, market open, market close, and post-market times, for a given date range and timezone. ```python import pandas_market_calendars as mcal NYSE = mcal.get_calendar("NYSE") nyse_schedule = NYSE.schedule("2012-07-02", "2012-07-05", market_times="all", tz=NYSE.tz) nyse_schedule ``` -------------------------------- ### Get Trading Schedule with Intraday Breaks Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Fetches the trading schedule for a specific exchange, including details on intraday market breaks. This is useful for markets with non-continuous trading sessions. ```python cme = mcal.get_calendar("CME_Equity") schedule = cme.schedule("2020-01-01", "2020-01-04") schedule ``` -------------------------------- ### Access Current Market Open Time Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieve the current market open time by accessing the 'market_open' key directly from the market object. This provides a quick way to get the standard opening time. ```python nyse["market_open"] ``` -------------------------------- ### Get Market Open Time for a Specific Date Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieves the market open time for a particular date. This is helpful for checking opening times on specific historical or future dates. ```python nyse["market_open", "1950-01-01"] # gets the time on a certain date ``` ```default datetime.time(10, 0, tzinfo=) ``` -------------------------------- ### Get Current Market Open and Close Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieve the current `open_time` and `close_time` for a market. These attributes reflect the standard opening and closing times configured for the market object. ```python nyse.open_time, nyse.close_time ``` -------------------------------- ### Get LSE Market Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieves the trading schedule for the London Stock Exchange (LSE) between specified dates. The output includes market open and close times. ```python import pandas_market_calendars as mcal lse = mcal.get_calendar('LSE') schedule_lse = lse.schedule('2015-12-20', '2016-01-06') schedule_lse ``` -------------------------------- ### Get Market Schedule with Default Order Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the market schedule for a given date range using default column ordering. Note that 'changes_and_offset' may not be in the expected order for earlier dates. ```python cal.schedule("2009-12-23", "2009-12-29", market_times="all") ``` -------------------------------- ### Get Market Times on a Specific Date Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieve the market open time on a specific date using `open_time_on`, or a general market time (like 'market_close') on a specific date using `get_time_on`. These methods allow historical time lookups. ```python # open_time_on looks for market_open, close_time_on looks for market_close and get_time_on looks for the provided market time nyse.open_time_on("1950-01-01"), nyse.get_time_on("market_close", "1960-01-01") ``` -------------------------------- ### Get the first trading day of every week Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the first trading day for each week within a specified date range, using the 'left' closed interval. ```python # The First Trading Day of every Week in the range nyse.date_range_htf("1W", start="2016-12-20", end="2017-01-10", closed="left") ``` -------------------------------- ### Get Market Open Time for a Specific Date Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieve the market open time for a particular date by specifying the date string along with the 'market_open' key. This allows for precise historical time retrieval. ```python nyse["market_open", "1950-01-01"] ``` -------------------------------- ### Generate business days using date_range_htf with start and end dates Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Demonstrates the use of date_range_htf to get valid business days within a specified range, similar to pandas.date_range. ```python # date_range_htf() is functionally identical to valid_days() when given a frequency of '1D', a Start, and End Date nyse.date_range_htf("1D", start="2016-12-20", end="2017-01-10") ``` -------------------------------- ### Initialize and List Market Calendars Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/README.rst Retrieve a specific exchange calendar and list all available calendars supported by the package. ```python import pandas_market_calendars as mcal # Create a calendar nyse = mcal.get_calendar('NYSE') # Show available calendars print(mcal.get_calendar_names()) ``` -------------------------------- ### Get valid business days within a date range Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves a DatetimeIndex of valid open business days between a specified start and end date, excluding weekends and holidays. ```python nyse.valid_days(start_date="2016-12-20", end_date="2017-01-10") ``` -------------------------------- ### Get Specific Market Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieve only specific market times like 'post' and 'market_open'. The order of times in the output will match the order specified in the 'market_times' argument. Note that times are not adjusted for special opens/closes if only specific times are requested. ```python # specific market times # CAVEAT: Looking at 2012-07-03, you can see that times will NOT be adjusted to special_opens/sepcial_closes # if market_open/market_close are not requested specific = nyse.schedule(start_date='2012-07-01', end_date='2012-07-10', market_times= ["post", "market_open"]) # this order will be kept specific ``` -------------------------------- ### Get Market Schedule with Custom Column Order Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the market schedule, allowing for a custom order of market time columns by passing a list to the 'market_times' argument. ```python cal.schedule( "2009-12-23", "2009-12-29", market_times=["with_offset", "market_open", "market_close", "changes_and_offset"] ) ``` -------------------------------- ### Create Schedule from Quarterly Date Range (NYSE) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Demonstrates creating a trading schedule from a date range generated by `date_range_htf` with a quarterly frequency. This allows for generating schedules for specific financial quarters. ```python # But This method can produce a schedule from any range produced by date_range_htf() dates = nyse.date_range_htf("Q", start="2017-01-01", end="2018-01-10") nyse.schedule_from_days(dates) ``` -------------------------------- ### Attempt to Add Existing Custom Time Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb This example shows the behavior when trying to assign a value to an existing custom time key ('post'). An `AssertionError` is raised, indicating that the time already exists. Use `.change_time` for explicit modification. ```python try: nyse["post"] = time(19) except AssertionError as e: print(e) ``` -------------------------------- ### Get Specific Market Times on a Date Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Use `open_time_on`, `close_time_on`, and `get_time_on` to retrieve the specific market open, close, or other defined times for a given date. This is useful for historical time lookups. ```python nyse.open_time_on("1950-01-01"), nyse.get_time_on("market_close", "1960-01-01") ``` -------------------------------- ### Get Market Schedule with Specific Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Use the schedule method to retrieve market open and close times for a given date range. The market_times parameter allows specifying which trading times to include. ```python cal.schedule("2009-12-23", "2009-12-28", market_times= ["changes_and_offset", "market_close"], force_special_times= None) ``` -------------------------------- ### Initialize XKRX Market Calendar Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Initializes the XKRX market calendar. This may trigger a UserWarning for discontinued market times. ```python xkrx = mcal.get_calendar("XKRX") ``` -------------------------------- ### Generate Date Range with Custom Start, Periods, and Frequency Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Use the date_range function with custom start time, number of periods, and a specified frequency. The 'closed' parameter controls whether the start or end of the interval is inclusive. ```python mcal.date_range( nyse_schedule, frequency="1h", start="2012-07-02 13:30:00-04:00", periods=8, closed="left", force_close=False ) ``` -------------------------------- ### Check Market Open Times with Interruptions Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Demonstrates how `MarketCalendar.open_at_time` respects interruptions by checking market open status at specific timestamps. Ensure your schedule is correctly configured. ```python is_open(cal, sched, "2010-01-12 14:00:00", "2010-01-12 14:35:00","2010-01-13 15:59:00","2010-01-13 16:30:00") ``` ```default open on 2010-01-12 14:00:00 : False open on 2010-01-12 14:35:00 : True open on 2010-01-13 15:59:00 : False open on 2010-01-13 16:30:00 : True ``` -------------------------------- ### Add Market Times with Different Formats Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Illustrates adding market times using various formats: just a time, a time with an offset, and complex changes with offsets. This showcases the flexibility of `add_time`. ```python cal.add_time("just_time", time(10)) cal.add_time("with_offset", (time(10), -1)) cal.add_time("changes_and_offset", ((None, time(17)), ("2009-12-28", time(11), -2))) print(cal.regular_market_times) ``` -------------------------------- ### Add and Check Custom Market Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Demonstrates adding a custom time using `add_time` and then checking for custom times using `has_custom` and `is_custom`. This allows for defining and verifying non-standard market time entries. ```python options.add_time("post", time(17)) ``` ```python options.has_custom, options.is_custom("market_open"), options.is_custom("post") ``` -------------------------------- ### Get Specific Market Close Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieve all historical times for a specific market event, such as 'market_close', for a given calendar. Set `all_times=True` to get all recorded times. ```python print(nyse.get_time("market_close", all_times=True)) # all_times = False only returns current ``` -------------------------------- ### Get Trading Schedule for a Specific Date Range (NYSE) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the market open and close times for a given date range using the NYSE calendar. This is useful for understanding trading hours on specific days. ```python schedule = nyse.schedule(start_date="2016-12-30", end_date="2017-01-10") schedule ``` -------------------------------- ### Conditional Schedule Difference Check Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Use `is_different` with comparison functions like `pd.Series.lt` for more granular control over identifying schedule differences. This example checks for order acceptance times that are strictly less than regular times. ```python schedule[options.is_different(schedule["order_acceptance"], pd.Series.lt)] ``` -------------------------------- ### Import Style for Functions and Classes Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/AGENTS.md Demonstrates the correct way to import functions and classes from internal modules. Use namespace imports for functions and direct imports for classes and exceptions. ```python # ✅ Functions from pandas_market_calendars import calendar_utils result = calendar_utils.merge_schedules(...) ``` ```python # ✅ Classes/Exceptions from pandas_market_calendars.market_calendar import MarketCalendar cal = MarketCalendar() ``` ```python # ❌ Wrong from pandas_market_calendars.calendar_utils import merge_schedules ``` -------------------------------- ### Generate Date Range with Start Timestamp without TZ Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates a date range using a specified frequency and a start timestamp without timezone information. These timestamps are interpreted in the timezone provided by the schedule. ```python # Start/End Timestamps without TZ information are interpreted in the timezone given by the schedule. mcal.date_range(nyse_schedule, frequency="1h", start="2012-07-02 13:30", periods=8, closed="left", force_close=False) ``` -------------------------------- ### Get Early Closes from Extended Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Identify and display early closing times from an extended market schedule that includes pre and post-market hours. This helps in pinpointing early closes within the broader trading day context. ```python nyse.early_closes(schedule=extended) ``` -------------------------------- ### Instantiate Calendar Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Create an instance of a custom MarketCalendar subclass. ```python cal = InterruptionsDemo() ``` -------------------------------- ### Handle Insufficient Schedule Warnings Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Demonstrates how to catch and process InsufficientScheduleWarning exceptions when generating market schedules. This is useful when the requested date range might be slightly off, requiring an adjustment to fetch additional dates. ```python try: nyse_schedule = NYSE.schedule("2012-07-02", "2012-07-05", market_times="all", tz=NYSE.tz) dt = problematic_date_range_args() except mcal_util.InsufficientScheduleWarning as w: # When this Warning is thrown from a date_range call that requests a # of periods # it over estimates the needed date by about 1 week to ensure that a second warning # is not thrown when doing this. beginning, start, end = mcal_util.parse_insufficient_schedule_warning(w) extra_dates_needed = NYSE.schedule(start, end, tz=NYSE.tz, market_times="all") if beginning: nyse_schedule = pd.concat([extra_dates_needed, nyse_schedule]) else: nyse_schedule = pd.concat([nyse_schedule, extra_dates_needed]) # Call the Function again to get the desired result dt = problematic_date_range_args() dt ``` -------------------------------- ### Get LSE Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the trading schedule for the LSE between specified dates. This is a prerequisite for merging schedules. ```python # LSE Calendar lse = mcal.get_calendar("LSE") schedule_lse = lse.schedule("2015-12-20", "2016-01-06") schedule_lse ``` -------------------------------- ### Get NYSE Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the trading schedule for the NYSE between specified dates. This is a prerequisite for merging schedules. ```python # NYSE Calendar nyse = mcal.get_calendar("NYSE") schedule_nyse = nyse.schedule("2015-12-20", "2016-01-06") schedule_nyse ``` -------------------------------- ### Handle Missing Order Acceptance in Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Illustrates the error handling for `open_at_time` when the provided schedule is not based on `market_times` or lacks entries in `open_close_map`. This typically results in a `ValueError`. ```python sched = cal.schedule("2010-01-09", "2010-01-15", start= "order_acceptance", interruptions= True) try: cal.open_at_time(sched, "2010-01-12") except ValueError as e: print(e) ``` ```default You seem to be using a schedule that isn't based on the market_times, or includes market_times that are not represented in the open_close_map. ``` -------------------------------- ### Get Exchange Holidays Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Access the list of holidays for a given exchange calendar. This helps in identifying non-trading days. ```python holidays = nyse.holidays() holidays.holidays[-5:] ``` -------------------------------- ### Respect Interruptions with open_at_time Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Demonstrates how `MarketCalendar.open_at_time` respects defined interruptions when checking market open status. ```python is_open(cal, sched, "2010-01-12 14:00:00", "2010-01-12 14:35:00", "2010-01-13 15:59:00", "2010-01-13 16:30:00") ``` -------------------------------- ### Get Exchange Time Zone Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieve the time zone associated with a specific exchange calendar. This is useful for time-sensitive operations. ```python nyse.tz.zone ``` -------------------------------- ### Dynamically Changing Trading Hours Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Demonstrates how to dynamically change trading hours using `change_time` to disable 'order_acceptance' and then re-enabling it. This affects subsequent schedule calculations. ```python cal.change_time("order_acceptance", cal["order_acceptance"], opens= False) is_open(cal, sched, "2010-01-11 13:35:00", "2010-01-12 14:35:00", "2010-01-13 15:59:00", "2010-01-13 16:30:00") ``` ```default open on 2010-01-11 13:35:00 : False open on 2010-01-12 14:35:00 : True open on 2010-01-13 15:59:00 : False open on 2010-01-13 16:30:00 : True ``` -------------------------------- ### Get the last trading day of every week Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Fetches the last trading day for each week within a specified date range. ```python # The Last Trading Day of every Week in the range nyse.date_range_htf("1W", start="2016-12-20", end="2017-01-10") ``` -------------------------------- ### Custom Session Names Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Illustrates how to provide user-defined names for trading sessions using an optional dictionary when generating date ranges. ```python # User Defined Names for each session can be passed in an optional dictionary ``` -------------------------------- ### Generate Market Schedule with Default Order Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Generates a market schedule for a given date range using default ordering of market times. Useful for a standard overview of market open and close times. ```python cal.schedule("2009-12-23", "2009-12-29", market_times= "all") ``` -------------------------------- ### Define Market Interruptions Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Subclasses can define interruptions in the `interruptions` property. This example shows how to define multiple interruption periods for a custom calendar. ```python class InterruptionsDemo(DemoOptionsCalendar): @property def interruptions(self): return [ ("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))] ``` -------------------------------- ### Add and Access a New Custom Market Time Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Demonstrates adding a new custom market time, 'new_post', with a specific time value. The added time can then be accessed directly using its key. ```python nyse["new_post"] = time(20) ``` ```python nyse["new_post"] ``` -------------------------------- ### Initialize Calendar and Handle Discontinued Times Warning Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Initializes a market calendar and shows a warning for discontinued market times. This indicates that certain time fields are deprecated. ```python xkrx = mcal.get_calendar("XKRX") ``` ```default /opt/hostedtoolcache/Python/3.10.9/x64/lib/python3.10/site-packages/pandas_market_calendars/market_calendar.py:144: UserWarning: ['break_start', 'break_end'] are discontinued, the dictionary .discontinued_market_times has the dates on which these were discontinued. The times as of those dates are incorrect, use .remove_time(market_time) to ignore a market_time. warnings.warn(f"{list(discontinued.keys())} are discontinued, the dictionary" ``` -------------------------------- ### Retrieve Specific Market Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Use `get_time` to retrieve specific market times like 'pre' (pre-market) or 'post' (post-market) for the current day. These times are also dynamic and reflect the current configuration. ```python nyse.get_time("post"), nyse.get_time("pre") # these also refer to the current time ``` -------------------------------- ### Get NYSE Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieve the trading schedule for the NYSE for a specified date range. This function returns a DataFrame with market open and close times. ```python # NYSE Calendar nyse = mcal.get_calendar('NYSE') schedule_nyse = nyse.schedule('2015-12-20', '2016-01-06') schedule_nyse ``` -------------------------------- ### Import New Calendar Class Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/new_market.md Import your newly created calendar class into the calendar registry. ```python from .exchange_calendar_xxx import XXXExchangeCalendar ``` -------------------------------- ### Get Schedule After Removing Discontinued Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieves the trading schedule after removing discontinued time fields. The output table will no longer contain these fields. ```python xkrx.schedule("2020-01-01", "2020-01-05") ``` ```html
market_open market_close
2020-01-02 2020-01-02 00:00:00+00:00 2020-01-02 06:30:00+00:00
2020-01-03 2020-01-03 00:00:00+00:00 2020-01-03 06:30:00+00:00
``` -------------------------------- ### Get Schedule with Discontinued Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieves the trading schedule for a given date range, including discontinued time fields like 'break_start' and 'break_end'. ```python xkrx.schedule("2020-01-01", "2020-01-05") ``` ```html
market_open break_start break_end market_close
2020-01-02 2020-01-02 00:00:00+00:00 2020-01-02 03:00:00+00:00 2020-01-02 04:00:00+00:00 2020-01-02 06:30:00+00:00
2020-01-03 2020-01-03 00:00:00+00:00 2020-01-03 03:00:00+00:00 2020-01-03 04:00:00+00:00 2020-01-03 06:30:00+00:00
``` -------------------------------- ### View Regular Market Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Inspect the predefined regular market opening and closing times for an exchange. Refer to 'Customizations' for more details. ```python print(nyse.regular_market_times) ``` -------------------------------- ### Instantiate Calendar and View Interruptions Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Instantiate a calendar with custom interruptions and access the `interruptions_df` property to view them in a DataFrame format. ```python cal = InterruptionsDemo() ``` ```python cal.interruptions_df ``` -------------------------------- ### Get Special Dates for Order Acceptance Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves special dates related to order acceptance for a given date range. Ensure the date format is correct. ```python options.special_dates("order_acceptance", "2000-12-22", "2001-12-28") ``` -------------------------------- ### Add New Closing Time and Regenerate Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Resets 'order_acceptance' to open and adds a new 'order_closed' time using `add_time`. A new schedule is then generated to reflect these changes, showing the impact on trading hours. ```python cal.change_time("order_acceptance", cal["order_acceptance"], opens=True) cal.add_time("order_closed", time(8), opens=False) sched = cal.schedule("2010-01-09", "2010-01-15", start="order_acceptance") sched ``` -------------------------------- ### Handle Missing Order Acceptance in Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Attempting to use `open_at_time` with a schedule that lacks 'order_acceptance' information will raise a ValueError. This demonstrates how to catch and handle this specific error. ```python sched = cal.schedule("2010-01-09", "2010-01-15", start="order_acceptance", interruptions=True) try: cal.open_at_time(sched, "2010-01-12") except ValueError as e: print(e) ``` -------------------------------- ### Get Valid Business Days Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Determine the valid business days for trading within a specified date range. Excludes weekends and holidays like Christmas. ```python nyse.valid_days(start_date='2016-12-20', end_date='2017-01-10') ``` -------------------------------- ### Generate Daily Date Range (Default) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates a DatetimeIndex of market close times for each trading day in the schedule. Uses default parameters 'closed="right"' and 'force_close=True'. ```python mcal.date_range(nyse_schedule, frequency="1D") ``` -------------------------------- ### Define Custom Calendar with Order Acceptance Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Creates a custom market calendar by inheriting from an existing one and overriding the open_close_map to include 'order_acceptance'. This allows for more granular scheduling. ```python class OpenCloseDemo(InterruptionsDemo): open_close_map = {**CFEExchangeCalendar.open_close_map, "order_acceptance": True} cal = OpenCloseDemo() sched = cal.schedule("2010-01-09", "2010-01-15", start="order_acceptance", interruptions=True) sched ``` -------------------------------- ### Customizing Market Calendar with Order Acceptance Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Defines a custom market calendar by inheriting from an existing one and adding 'order_acceptance' to the open_close_map. This allows scheduling based on custom trading hours. ```python class OpenCloseDemo(InterruptionsDemo): open_close_map = {**CFEExchangeCalendar.open_close_map, "order_acceptance": True} cal = OpenCloseDemo() sched = cal.schedule("2010-01-09", "2010-01-15", start= "order_acceptance", interruptions= True) sched ``` -------------------------------- ### Get Specific Market Time Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieve a specific market time, such as 'market_close', for a calendar using the `get_time` method. Set `all_times=True` to retrieve all historical time entries. ```python print(nyse.get_time("market_close", all_times= True)) # all_times = False only returns current ``` -------------------------------- ### Customize Market Calendar Open and Close Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Creates a custom market calendar with specified open and close times for regular trading hours. This modifies the default open and close times of the calendar. ```python cal = mcal.get_calendar("NYSE", open_time=time(10, 0), close_time=time(14, 30)) print("open, close: %s, %s" % (cal.open_time, cal.close_time)) ``` -------------------------------- ### Generate Market Schedule with Custom Time Order Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Generates a market schedule with a custom order for market times. This is useful when specific columns need to be prioritized or displayed in a particular sequence. ```python cal.schedule("2009-12-23", "2009-12-29", market_times= ["with_offset", "market_open", "market_close", "changes_and_offset"]) ``` -------------------------------- ### Checking Market Open Status with Custom Hours Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Verifies if the market was open at specific times, considering both interruptions and custom trading hours like 'order_acceptance'. ```python is_open(cal, sched, "2010-01-11 13:35:00", "2010-01-12 14:35:00", "2010-01-13 15:59:00", "2010-01-13 16:30:00") ``` ```default open on 2010-01-11 13:35:00 : True open on 2010-01-12 14:35:00 : True open on 2010-01-13 15:59:00 : False open on 2010-01-13 16:30:00 : True ``` -------------------------------- ### Get Special Dates for Order Acceptance Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/docs/usage.md Retrieves special dates related to order acceptance within a specified date range. This is useful for understanding trading cut-off times. ```python options.special_dates("order_acceptance", "2000-12-22", "2001-12-28") ``` ```default 2000-12-27 2000-12-27 14:30:00+00:00 2001-12-27 2001-12-27 14:30:00+00:00 dtype: datetime64[ns, UTC] ``` -------------------------------- ### Schedule with force_special_times=None Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the market schedule without adjusting any columns for special times, leaving both 'changes_and_offset' and 'market_close' as they are. ```python # None - will not adjust any column (both are left alone) cal.schedule("2009-12-23", "2009-12-28", market_times=["changes_and_offset", "market_close"], force_special_times=None) ``` -------------------------------- ### Generate Daily Date Range (Left Closed) Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Generates a DatetimeIndex of market open times for each trading day. Uses 'closed="left"' and 'force_close=False' for start-of-day timestamps. ```python mcal.date_range(nyse_schedule, frequency="1D", closed="left", force_close=False) ``` -------------------------------- ### Retrieve Market Schedule Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/README.rst Fetch the market open and close times for a specific exchange within a defined date range. ```python early = nyse.schedule(start_date='2012-07-01', end_date='2012-07-10') early ``` -------------------------------- ### Define Market Interruptions Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Subclasses of MarketCalendar can define interruptions using the `interruptions` property. This property should return a list of tuples, where each tuple specifies the date, start time, and end time of an interruption. ```python class InterruptionsDemo(DemoOptionsCalendar): @property def interruptions(self): return [ ("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)), ] ``` -------------------------------- ### Retrieve All Market Open Times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Access all recorded market open times, including historical data, by using the key 'market_open' with the 'all' parameter. This returns a tuple of tuples, each containing a date and a time. ```python nyse["market_open", "all"] ``` -------------------------------- ### Get the first trading day of every third quarter Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Retrieves the first trading day of every third quarter within a specified date range, using the 'left' closed interval. ```python # The First Trading Day of every Third Quarter in the range nyse.date_range_htf("3Q", start="2017-01-01", end="2025-01-01", closed="left") ``` -------------------------------- ### Print Default Calendar Open/Close Map Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Displays the default open and close times for a market calendar. This is useful for understanding the base trading schedule before any modifications. ```python print(cal.open_close_map) ``` -------------------------------- ### Check Market Open Status with New Closing Time Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Tests the market's open status after adding a new 'order_closed' time. This verifies that the new closing time is correctly incorporated into the trading schedule. ```python is_open(cal, sched, "2010-01-11 13:35:00", "2010-01-11 14:15:00", "2010-01-11 14:35:00") ``` -------------------------------- ### View regular market times Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Prints the defined regular market times for the exchange, including pre-market, market open, market close, and post-market. ```python print(nyse.regular_market_times) # more on this under the 'Customizations' heading ``` -------------------------------- ### Import necessary libraries Source: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb Imports the required libraries for using pandas_market_calendars, including pandas and datetime. ```python import sys sys.path.append("../") from datetime import time import pandas as pd import pandas_market_calendars as mcal ```