如何在Python中找到每个月的第一个市场日?

问题描述 投票:0回答:1

我试图弄清楚如何找到每个月的第一个市场日,并在运行一些逻辑后等到每一天。我已经找到了一些能够做到这一点的代码,但是我无法让代码能够成为我可以在服务器或其他东西上每月运行的东西。

这是迄今为止我的代码:

    nyse = mcal.get_calendar("XNYS")
    # Get the current time
    current_time = pd.Timestamp.now(tz="America/New_York").tz_localize(None)  # Ensure timezone-naive

    # Find the first market day of the coming month
    current_month = current_time.month
    current_year = current_time.year
    next_month = current_month + 1 if current_month < 12 else 1
    next_year = current_year + 1 if current_month == 12 else current_year

    # Initialize a variable to store the first market day
    first_market_day_next_month = None

    # Iterate through each day of the coming month until we find a market trading day
    for day in range(1, 32):
        try:
            date_candidate = pd.Timestamp(year=next_year, month=next_month, day=day)
            date_candidate = nyse.valid_days(start_date=date_candidate, end_date=date_candidate).tz_localize(None)  # Ensure timezone-naive
            if date_candidate is not None:
                first_market_day_next_month = date_candidate
                break
        except ValueError:
            # Handles cases where the day is out of range for the month
            pass
    first_market_day_next_month=first_market_day_next_month[0]
    market_open_time = nyse["market_open", f"{first_market_day_next_month}"]
    first_market_day_next_month=first_market_day_next_month.to_pydatetime()

    market_open_timestamp = pd.to_datetime(f'{first_market_day_next_month} {market_open_time}', format='mixed')

    # Calculate the time difference in seconds
    if market_open_timestamp is not None:
        time_difference_seconds = (market_open_timestamp - current_time).total_seconds()
        print("Time until market open on the first market day of the coming month (NYSE):", time_difference_seconds, "seconds")
    else:
        print("Unable to determine the first market day of the coming month.")
    return int(time_difference_seconds)

此代码适用于该代码的一次迭代,但不适用于每月。 我需要调整什么才能做到这一点?

python pandas datetime python-datetime
1个回答
0
投票

使用 numpy.datetime 中的工作日功能可以非常简单地完成此操作。

示例:

输入:

np.busday_offset('2024-05-01', 0, 'forward')

输出:

numpy.datetime64('2024-05-01')

输入:

np.busday_offset('2024-06-01', 0, 'forward') # This is a Saturday

输出:

numpy.datetime64('2024-06-03')

可以使用 numpy.busdaycalendar

添加特定假期
© www.soinside.com 2019 - 2024. All rights reserved.