【问题标题】:RRule set for days and hours in dayRRule 设置为一天中的天数和小时数
【发布时间】:2013-03-17 23:18:31
【问题描述】:

我正在使用 python 的规则来计算交易时间。这几天很容易,我正在使用我在这个网站上找到的一个稍微修改过的例子:

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 byday 和 byhour 混合使用,但我找不到任何好的例子。

非常欢迎任何帮助!

【问题讨论】:

    标签: python datetime forex 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 2013-09-16
      • 1970-01-01
      • 2015-05-09
      相关资源
      最近更新 更多