使用熊猫市场日历获取下一个交易日

时间:2019-12-16 16:05:37

标签: python pandas date

我想修改以下代码,以便我可以从现在开始或在n天之前获得交易日:

import pandas_market_calendars as mcal
holidays = nyse.holidays()
mydate = pd.to_datetime("12/24/2019")
holidays(mydate)
Timestamp('2019-12-26 00:00:00')

是否可以提供天数作为holiday()的参数?

我可以像这样在联邦假期工作:

from pandas.tseries.holiday import USFederalHolidayCalendar
bday_us1 = CustomBusinessDay(calendar=USFederalHolidayCalendar(), n=2)
mydate + bday_us1
Timestamp('2019-12-27 00:00:00')

3 个答案:

答案 0 :(得分:0)

我假设您已经在某处有此行:

nyse = mcal.get_calendar('NYSE')

您可能正在寻找的东西是这样的:

nyse.valid_days(start_date='2016-12-20', end_date='2017-01-10')

这将返回所有有效日期(非节假日)以及开始日期和结束日期的列表。 要获取此日期范围:

mydate = pd.to_datetime("12/24/2019")
d = datetime.timedelta(days = 10)
start_date = mydate - d
end_date = mydate + d

答案 1 :(得分:0)

没有holidays方法采用日期范围。以当前日期为基础,我们可以生成包含5天前和5天前的日期列表。然后,对于每一天,我们将下一个假期收集到set中,以避免重复。 (可选)我们对获得的list进行排序,因为set不能保持顺序。

import pandas_market_calendars as mcal
import pandas as pd
from datetime import timedelta

mydate = pd.to_datetime("12/24/2019")
nyse = mcal.get_calendar('NYSE')
holidays = nyse.holidays()

delta = timedelta(5)
start = mydate - delta
end = mydate + delta

date_list = [end - (timedelta(x)) for x in range((end-start).days)]
holidays = list(set(holidays(d) for d in date_list))
for day in sorted(holidays):
    print(day)

输出

2019-12-23 00:00:00
2019-12-24 00:00:00
2019-12-26 00:00:00
2019-12-27 00:00:00
2019-12-30 00:00:00

答案 2 :(得分:0)

我找到了一个可行的解决方案,我只是在函数内使用有效交易日的日期,而不是假期:

def next_business_day(start_day, business_days, HOLIDAYS):
    ONE_DAY = datetime.timedelta(days=1)
    temp_day = start_day
    for i in range(0, business_days):
        next_day = temp_day + ONE_DAY
        while next_day.weekday() in [5,6] or next_day not in nyse.valid_days(start_date='2000-12-20', end_date='2020-01-10'):
            next_day += ONE_DAY
        temp_day = next_day
    return temp_day 

请注意,这是基于来自另一个论坛的帖子,其中使用了假期:

def next_business_day(start_day, business_days, HOLIDAYS):
    ONE_DAY = datetime.timedelta(days=1)
    temp_day = start_day
    for i in range(0, business_days):
        next_day = temp_day + ONE_DAY
        while next_day.weekday() in [5,6] or next_day in HOLIDAYS:
            next_day += ONE_DAY
        temp_day = next_day
    return temp_day