尽管还是个菜鸟,我已经热情地学习 Python 一段时间了,这是我正在做的一个项目。我需要收集过去二十年美国公共假期前十天的历史股票价格,这就是我所做的:(我在这里使用了pandas_datareader和假期)
start=datetime.datetime(1995,1,1)
end=datetime.datetime(2015,12,31)
history_price=web.get_data_yahoo('SPY', start, end)
us_holidays=holidays.UnitedStates()
test=[]
for i in dates:
if i in us_holidays:
test.append((history_price['Adj Close'].ix[pd.date_range(end=i, periods=11, freq='B')]))
test
结果是这样的:
Freq: B, Name: Adj Close, dtype: float64, 1995-02-06 32.707565
1995-02-07 32.749946
1995-02-08 32.749946
1995-02-09 32.749946
1995-02-10 32.792328
1995-02-13 32.802975
1995-02-14 32.845356
1995-02-15 33.025457
1995-02-16 32.983076
1995-02-17 32.855933
1995-02-20 NaN
列表“test”的长度是233。我的问题是:如何将此列表转换为字典,其中假期为键,股票价格为每个键下的值。
提前感谢您的指导。
这使用字典和列表理解来生成每个假期之前的一组十个美国工作日。然后,这些天的股票价格将作为价格列表存储在字典中(节假日键入),最近的在前 (h-1),较早的在最后 (h-10)。
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
holidays = USFederalHolidayCalendar().holidays(start='1995-1-1', end='2015-12-31')
bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())
start = '1995-01-01'
end = '2015-12-31'
days = 10
dates = {holiday: [holiday - bday_us * n for n in range(1, days + 1)]
for holiday in USFederalHolidayCalendar().holidays(start=start, end=end)}
>>> dates
{...
Timestamp('2015-12-25 00:00:00'): [
Timestamp('2015-12-24 00:00:00'),
Timestamp('2015-12-23 00:00:00'),
Timestamp('2015-12-22 00:00:00'),
Timestamp('2015-12-21 00:00:00'),
Timestamp('2015-12-18 00:00:00'),
Timestamp('2015-12-17 00:00:00'),
Timestamp('2015-12-16 00:00:00'),
Timestamp('2015-12-15 00:00:00'),
Timestamp('2015-12-14 00:00:00'),
Timestamp('2015-12-11 00:00:00')]}
result = {holiday: history_price.ix[dates[holiday]].values for holiday in dates}
>>> result
{...
Timestamp('2015-12-25 00:00:00'):
array([ 203.56598 , 203.902497, 201.408393, 199.597201, 197.964166,
201.55487 , 204.673725, 201.722125, 199.626485, 198.622952])}
我刚刚找到了一个可能对您有帮助的软件包。
n
中的day_delta
表示10个工作日前。周末不包含在n
计数中!
! pip install finter
from finter.framework_model import TradingDay, iter_trading_days
holiday = "20240101"
start = TradingDay.day_delta(holiday, n=-10, exchange="us") # 10 business day before
iter_trading_days(start, holiday, exchange="us")
这是免费的 API。 https://quantit.gitbook.io/finter/calendar