计算当月已过去的交易日数量,核心逻辑是先确定当月的所有交易日,再筛选出小于等于当前日期的交易日进行计数,需要排除周末和法定节假日的影响。

基础实现思路
整个计算流程可以分为三个步骤:
- 获取当前日期和当月的第一天、最后一天日期
- 获取对应月份的完整交易日历,排除周末和法定节假日
- 统计交易日历中日期小于等于当前日期的数量
基于本地交易日历的实现
如果业务场景不需要实时更新节假日数据,可以提前维护一份交易日历文件,比如用CSV格式存储每年的交易日日期,每行一个日期,格式为YYYY-MM-DD。
核心代码示例(Python)
以下代码实现读取本地交易日历文件,统计当月已过去的交易日数量:
import datetime
import csv
def count_passed_trading_days(local_calendar_path):
# 获取当前日期
today = datetime.date.today()
# 获取当月第一天
first_day_of_month = today.replace(day=1)
# 获取当月最后一天
if today.month == 12:
last_day_of_month = today.replace(year=today.year+1, month=1, day=1) - datetime.timedelta(days=1)
else:
last_day_of_month = today.replace(month=today.month+1, day=1) - datetime.timedelta(days=1)
# 读取本地交易日历
trading_days = []
with open(local_calendar_path, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
if row:
day_str = row[0].strip()
try:
day = datetime.datetime.strptime(day_str, '%Y-%m-%d').date()
trading_days.append(day)
except ValueError:
continue
# 筛选当月的交易日
month_trading_days = [d for d in trading_days if first_day_of_month <= d <= last_day_of_month]
# 统计已过去的交易日
passed_trading_days = [d for d in month_trading_days if d <= today]
return len(passed_trading_days)
# 调用示例,假设交易日历文件放在当前目录的trading_calendar.csv
result = count_passed_trading_days('trading_calendar.csv')
print(f'当月已过去的交易日数量为:{result}')
基于第三方接口的实时实现
如果需要实时获取最新的节假日调整数据,比如遇到临时调休的情况,可以使用金融数据接口获取交易日历,这里以tushare接口为例,需要先安装tushare库并获取token。
核心代码示例(Python)
import datetime
import tushare as ts
def count_passed_trading_days_api(token):
# 初始化tushare
ts.set_token(token)
pro = ts.pro_api()
# 获取当前日期
today = datetime.date.today()
# 构造当月日期范围
start_date = today.strftime('%Y%m%d')
if today.month == 12:
end_month = today.replace(year=today.year+1, month=1, day=1) - datetime.timedelta(days=1)
else:
end_month = today.replace(month=today.month+1, day=1) - datetime.timedelta(days=1)
end_date = end_month.strftime('%Y%m%d')
# 获取交易日历,exchange参数为交易所代码,SSE代表上交所
df = pro.trade_cal(exchange='SSE', start_date=start_date, end_date=end_date)
# 筛选开盘日,is_open为1代表交易日
trading_days_df = df[df['is_open'] == 1]
# 转换日期格式
trading_days = [datetime.datetime.strptime(str(d), '%Y%m%d').date() for d in trading_days_df['cal_date']]
# 统计已过去的交易日
passed_trading_days = [d for d in trading_days if d <= today]
return len(passed_trading_days)
# 调用示例,替换为自己的tushare token
result = count_passed_trading_days_api('你的tushare_token')
print(f'当月已过去的交易日数量为:{result}')
注意事项
- 本地交易日历需要定期更新,尤其是遇到法定节假日调整、临时调休的时候,否则统计结果会有偏差
- 不同交易所的交易日历可能存在差异,需要根据业务对应的交易所选择对应的日历数据
- 如果当前日期是当月的第一天,且当天是交易日,统计结果应该为1,逻辑中需要包含当天日期的判断
- 代码中的日期比较需要注意格式统一,避免字符串和日期对象直接比较导致错误
扩展场景
如果需要计算任意月份、任意截止日期的已过去交易日数量,只需要把函数中的当前日期参数替换为传入的年份、月份、截止日期即可,核心逻辑不需要做大的调整。比如传入2024年5月15日,就可以统计2024年5月截止到15日的已过去交易日数量。