python 如何循环遍历一系列滚动日期?

rxztt3cl  于 2022-11-28  发布在  Python
关注(0)|答案(3)|浏览(178)

我在谷歌上搜索了一下,找到了如何生成一年中所有星期五的日期。

# get all Fridays in a year
from datetime import date, timedelta
def allfridays(year):
   d = date(year, 1, 1)               # January 1st              
   d += timedelta(days = 8 - 2)       # Friday   
   while d.year == year:
      yield d
      d += timedelta(days = 7)

      
for d in allfridays(2022):
   print(d)

结果:

2022-01-07
2022-01-14
2022-01-21
etc.
2022-12-16
2022-12-23
2022-12-30

现在,我正在尝试找出如何循环遍历一系列滚动日期,比如2022-01-07 + 60天,然后是2022-01-14 + 60天,然后是2022-01-21 + 60天。

step #1:
start = '2022-01-07'
end = '2022-03-08'

step #2:
start = '2022-01-14'
end = '2022-03-15'

理想情况下,我希望将开始和结束日期循环传递到另一个循环中,该循环如下所示...

price_data = []
for ticker in tickers:
    try:
        prices = wb.DataReader(ticker, start = start.strftime('%m/%d/%Y'), end = end.strftime('%m/%d/%Y'), data_source='yahoo')[['Adj Close']]
        price_data.append(prices.assign(ticker=ticker)[['ticker', 'Adj Close']])
    except:
        print(ticker)        
df = pd.concat(price_data)
lmyy7pcs

lmyy7pcs1#

首先,我们必须计算出如何得到给定年份的第一个星期五。接下来,我们将计算开始日和结束日。

import datetime

FRIDAY = 4  # Based on Monday=0
WEEK = datetime.timedelta(days=7)

def first_friday(year):
    """Return the first Friday of the year."""
    the_date = datetime.date(year, 1, 1)
    while the_date.weekday() != FRIDAY:
        the_date = the_date + datetime.timedelta(days=1)
    return the_date

def friday_ranges(year, days_count):
    """
    Generate date ranges that starts on first Friday of `year` and
    lasts for `days_count`.
    """
    DURATION = datetime.timedelta(days=days_count)

    start_date = first_friday(year)
    end_date = start_date + DURATION

    while end_date.year == year:
        yield start_date, end_date
        start_date += WEEK
        end_date = start_date + DURATION

for start_date, end_date in friday_ranges(year=2022, days_count=60):
    # Do what you want with start_date and end_date
    print((start_date, end_date))

示例输出:

(datetime.date(2022, 1, 7), datetime.date(2022, 3, 8))
(datetime.date(2022, 1, 14), datetime.date(2022, 3, 15))
(datetime.date(2022, 1, 21), datetime.date(2022, 3, 22))
...
(datetime.date(2022, 10, 21), datetime.date(2022, 12, 20))
(datetime.date(2022, 10, 28), datetime.date(2022, 12, 27))

备注

  • 第一个星期五的算法很简单:从1月1日开始,然后继续推进到星期五
  • 我假设结束日期必须在指定的年份内。
soat7uwm

soat7uwm2#

这也许可行,你可以在lambda函数中添加条件,循环的结尾.

from datetime import date, timedelta
    def allfridays(year):
       d = date(year, 1, 1)               # January 1st              
       d += timedelta(days = 8 - 2)       # Friday   
       while d.year == year:
          yield d
          d += timedelta(days = 7) 
    list_dates = []
    for d in allfridays(2022):
    list_dates.append(d)
    

    add_days = map(lambda x: x+timedelta(days = 60),list_dates)
    print(list(add_days))
zpqajqem

zpqajqem3#

哦,天哪,我以前完全错过了这个。下面的解决方案效果很好。

import pandas as pd
# get all Fridays in a year
from datetime import date, timedelta
def allfridays(year):
   d = date(year, 1, 1)               # January 1st              
   d += timedelta(days = 8 - 2)       # Friday   
   while d.year == year:
      yield d
      d += timedelta(days = 7)

lst=[]
for d in allfridays(2022):
    lst.append(d)
    
df = pd.DataFrame(lst)
print(type(df))
df.columns = ['my_dates']

df['sixty_ahead'] = df['my_dates'] + timedelta(days=60)
df 

Result:
      my_dates sixty_ahead
0   2022-01-07  2022-03-08
1   2022-01-14  2022-03-15
2   2022-01-21  2022-03-22
etc.
49  2022-12-16  2023-02-14
50  2022-12-23  2023-02-21
51  2022-12-30  2023-02-28

相关问题