2013-03-17 63 views
0

我使用python的rrule來計算交易時間。這很容易的日子裏,我使用了一個稍微修改的例子,我在這個非常網站上發現:RRule在天數和小時數設置

def get_rset(start_date):  
    # Create a rule to recur every weekday starting today 
    r = rrule.rrule(rrule.DAILY, 
        byweekday=[rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR], 
        dtstart=start_date) 
    # Create a rruleset 
    rs = rrule.rruleset() 
    # Attach our rrule to it 
    rs.rrule(r) 
    # Add holidays as exclusion days 
    for exdate in holidays: 
     rs.exdate(exdate) 
    return rs 

問題是,雖然這偉大工程的股份,我需要以不同的方式計算外匯日期。我需要每小時工作一次,在公共假期加入等。

在UTC我相信市場是從週日晚上10點開始到下週五晚上10點。

爲了做到這一點,我現在需要6個不同的日子,週日和週五需要特殊的時間,其餘的週一到週五都要考慮到所有的時間。我很確定,我需要在日間和時間之間混合使用rrule,但是我無法做到這一點。

任何幫助非常歡迎!

回答

1

我已經想出了一個更簡單的方法,在Google,代碼和類文檔中單獨使用一段時間。它使用一個輕微的(但適當的)作弊。請參閱以下示例解決方案。

from dateutil import rrule 
from datetime import timedelta , datetime 
holidays = [] # This is just a list of dates to exclude 

def datetime_in_x_trading_hours(start_dt,future_hours): 
    # First we add two hours. This is because its simpler to view the timeset 
    # as 24hrs MON - FRI. (This also helps align the dates for the holidays) 
    print start_dt 
    start_dt += timedelta(hours=2) 
    rs = get_fx_rset(start_dt) 
    # Now using the set get the desired time and put the the missing hours 
    future_time = rs[future_hours] 
    future_time -= timedelta(hours=2) 
    return future_time 

def get_fx_rset(start_date_time): 

    # Create a rule to recur every weekday starting today 
    r = rrule.rrule(rrule.HOURLY, 
        byweekday=[rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR], 
        byhour=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23], 
        byminute=[0], 
        bysecond=[0], 
        dtstart=start_date_time) 

    # Create a rruleset 
    rs = rrule.rruleset() 
    # Attach our rrule to it 
    rs.rrule(r) 
    # Add holidays as exclusion days 
    for exdate in holidays: 
     rs.exdate(exdate) 

    return rs 

today = datetime.now() - timedelta(days=2) 
print datetime_in_x_trading_hours(today, 7)