过去二十年假期前十天的历史股票价格

时间:2016-07-27 03:45:12

标签: python dictionary yahoo-finance

尽管仍然是一个菜鸟,但我一直热心地学习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.我的问题是:如何将此列表转换为字典,假日为关键字,股票价格为每个键下的值。

提前感谢您的指导。

1 个答案:

答案 0 :(得分:0)

这使用字典和列表推导来在每个假期之前生成一组十个美国工作日。然后将那些日子的股票价格存储在字典中(键入假日)作为价格列表,最近的第一个(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])}