我正在编写一个 Python 脚本,使用datetime
,holidays
并dateutil
确定YYYY-MM-DD
格式中的给定日期是否是交易假期。holidays
我正在使用生成器表达式从图书馆提供的默认假期列表中删除市场未关闭的假期,
import datetime, holidays
import dateutil.easter as easter
def to_date(date_string):
return datetime.datetime.strptime(date_string,'%Y-%m-%d').date()
def is_trading_holiday(date):
us_holidays = holidays.UnitedStates(years=date.year)
# generate list without columbus day and veterans day since markets are open on those days
trading_holidays = [ "Columbus Day", "Columbus Day (Observed)", "Veterans Day", "Veterans Day (Observed)"]
custom_holidays = [ date for date in us_holidays if us_holidays[date] not in trading_holidays ]
# add good friday to list since markets are closed on good friday
custom_holidays.append(easter.easter(year=date.year) - datetime.timedelta(days=2))
return date in custom_holidays
if __name__=="__main__":
first_date = to_date('2020-01-03')
second_date = to_date('2015-11-26') # Thanksgiving
third_date = to_date('2005-01-01') # New Years
fourth_date = to_date('2005-01-07')
print(is_trading_holiday(first_date))
print(is_trading_holiday(second_date))
print(is_trading_holiday(third_date))
print(is_trading_holiday(fourth_date))
我已经测试了各种日期,它似乎在所有情况下都有效,但只有一个。当我使用 2005 年的日期时,这个函数会爆炸并告诉我,
Traceback (most recent call last):
File "./test.py", line 26, in <module>
print(is_trading_holiday(third_date))
File "./test.py", line 11, in is_trading_holiday
custom_holidays = [ date for date in us_holidays if us_holidays[date] not in trading_holidays ]
File "./test.py", line 11, in <listcomp>
custom_holidays = [ date for date in us_holidays if us_holidays[date] not in trading_holidays ]
RuntimeError: dictionary changed size during iteration
我不知道 2005 年有什么特别之处导致这个功能崩溃,或者即使是这一年导致了这个问题(我已经测试了这个可以追溯到 70 年代的日期,并且它有效)。我没有修改我在生成器表达式中迭代的字典(否则,我认为不是?),所以我不确定这个错误试图告诉我什么。
有人知道这里发生了什么吗?我错过了一些明显的东西吗?