PythonPandas市场日历日计数(交易日与日历日)

2024-05-15 21:38:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在进行一些市场研究,我正在调查的变量之一是事件发生的时间分布(对数分布),并创建一个累积概率密度函数(时间函数)。(我只是将我的日期转换为:

A=datetime.strptime(UDate1[0],date_format) 
B=datetime.strptime(UDate2[0],date_format)

我可以这样减去:

C=(A-B).days

我得到了一个天数的整数(5,6,10,11,不管是什么)

然而,我的数据应该符合日志分布,因为我目前使用日历日,我的事件只发生在市场日。。。这是一个不可接受的错误源,它在我的分布中创建了空直方图(第6天和第7天总是零(周末),假日效应)

我无法用这种方法计算准确的累积分布函数,因此我最近下载了熊猫市场日历。有没有人有计算交易日和市场日的经验。例如,如果我看的是从2020年7月19日到2020年7月13日的时间。这将是12个日历日,但只有8个交易日


Tags: 函数formatdatetimedate市场时间事件对数
2条回答

熊猫市场日历信息如下: https://pypi.org/project/pandas-market-calendars/

首先,创建一个市场数据对象,如链接中所述:

import pandas_market_calendars as mcal

# Create a calendar
nyse = mcal.get_calendar('NYSE')

early = nyse.schedule(start_date='2012-07-01', end_date='2012-07-10')

print(mcal.date_range(early, frequency='1D'))

DatetimeIndex(['2012-07-02 20:00:00+00:00', '2012-07-03 17:00:00+00:00',
               '2012-07-05 20:00:00+00:00', '2012-07-06 20:00:00+00:00',
               '2012-07-09 20:00:00+00:00', '2012-07-10 20:00:00+00:00'],
              dtype='datetime64[ns, UTC]', freq=None)

现在,创建一个值为1的系列,并按市场天数进行索引。然后在日历天上重新编制索引,并用零填充缺少的值。计算累计金额,两个日期之间的交易天数是不同日期累计金额的差值:

import pandas as pd

bus_day_index = pd.DatetimeIndex(
    ['2012-07-02 20:00:00+00:00', '2012-07-03 17:00:00+00:00',
     '2012-07-05 20:00:00+00:00', '2012-07-06 20:00:00+00:00',
     '2012-07-09 20:00:00+00:00', '2012-07-10 20:00:00+00:00'],
    dtype='datetime64[ns, UTC]', freq=None)

bus_day_index = bus_day_index.normalize()

s = pd.Series(data=1, index=bus_day_index)

cal_day_index = pd.date_range(start=bus_day_index.min(), end=bus_day_index.max())

s = s.reindex(index=cal_day_index).fillna(0).astype(int)

s = s.cumsum()

s['2012-07-09'] - s['2012-07-03']

优点:这种(不雅观的)方法包含了工作日的非交易日(美国的阵亡将士纪念日、劳动节等)

从你的问题看来,你似乎想要计算交易日的数量。如果是,请尝试以下方法:

from datetime import datetime, date, timedelta

start_date = A
end_date = B
delta = timedelta(days=1)
count = 0
while start_date <= end_date:
    print (start_date.strftime("%Y-%m-%d"))
    if start_date.weekday() <=5:
       count +=1
    start_date += delta
print(count)

相关问题 更多 >