class TestCalendarWesternWeek(BaseCalendarTest):
    @classmethod
    def setup_class(cls):
        print('\n\nTesting regular week, Mo-Fr, no holidays, 2010-2013')

    def __init__(self):
        BaseCalendarTest.__init__(self)
        self.cal = Calendar()
        rr = rruleset()
        rr.rrule(rrule(DAILY,
                       byweekday=(MO,TU,WE,TH,FR),
                       dtstart=datetime.datetime(2010,1,1)))
        self.rr = rr
        self.dates = rr.between(datetime.datetime(2010,1,1),
                                datetime.datetime(2013,12,31),
                                inc=True)

    def test_workdaycount_with_non_workday_dates(self):
        print('test_workdaycount_with_non_workday_dates')
        """ Jan 30th and 31st fall on a weekend """
        daycount = 21;
        for date2 in ['Jan 30, 2010','Jan 31, 2010','Feb 1, 2010']:
            count = len(list(self.cal.range('2010-01-01', date2)));
            assert count == daycount
        for date2 in ['Jan 29, 2010','Jan 30, 2010','Jan 31, 2010']:
            count = self.cal.workdaycount('Dec 31, 2009', date2);
            assert count == daycount
class TestCalendarWesternWeek(BaseCalendarTest):
    @classmethod
    def setup_class(cls):
        print('\n\nTesting regular week, Mo-Fr, no holidays, 2010-2013')

    def __init__(self):
        BaseCalendarTest.__init__(self)
        self.cal = Calendar()
        rr = rruleset()
        rr.rrule(
            rrule(DAILY,
                  byweekday=(MO, TU, WE, TH, FR),
                  dtstart=datetime.datetime(2010, 1, 1)))
        self.rr = rr
        self.dates = rr.between(datetime.datetime(2010, 1, 1),
                                datetime.datetime(2013, 12, 31),
                                inc=True)

    def test_workdaycount_with_non_workday_dates(self):
        print('test_workdaycount_with_non_workday_dates')
        """ Jan 30th and 31st fall on a weekend """
        daycount = 21
        for date2 in ['Jan 30, 2010', 'Jan 31, 2010', 'Feb 1, 2010']:
            count = len(list(self.cal.range('2010-01-01', date2)))
            assert count == daycount
        for date2 in ['Jan 29, 2010', 'Jan 30, 2010', 'Jan 31, 2010']:
            count = self.cal.workdaycount('Dec 31, 2009', date2)
            assert count == daycount
Example #3
0
def main():
    """ Main example """
    logging.info("--- SETTING UP IDENTIFIERS ---")
    asset_manager_id = random.randint(1, 2**31 - 1)
    calendar = Calendar()
    # This can fail if yesterday was a holiday - need to add a holiday calendar
    business_date = calendar.addbusdays(date.today(), -2)
    logging.info("Business Date: %s", business_date)
    business_date_str = business_date.isoformat()
    symbols = ['TWTR', 'AAPL', 'RBS.L', 'Z77.SI', '0008.HK']

    logging.info("--- PULL MARKET DATA FROM YAHOO FINANCE ---")
    eod_prices = []
    for symbol in symbols:
        share = Share(symbol=symbol)
        logging.info("Stock Name: %s", share.get_name())
        close = (share.get_historical(
            start_date=business_date_str,
            end_date=business_date_str)[0].get('Close'))
        eod_price = EODPrice(asset_manager_id=asset_manager_id,
                             asset_id=symbol,
                             business_date=business_date,
                             price=Decimal(close))
        logging.info("EOD Price: %s", eod_price.price)
        eod_prices.append(eod_price)

    logging.info("--- PERSIST PRICES TO AMAAS ---")
    # Some of these attributes can be derived from the eod_prices - cleanup
    market_data_interface.persist_eod_prices(asset_manager_id=asset_manager_id,
                                             business_date=business_date,
                                             eod_prices=eod_prices,
                                             update_existing_prices=True)
class TestCalendarWesternWeekWithHolidays(BaseCalendarTest):
    @classmethod
    def setup_class(cls):
        print('\n\nTesting regular week, Mo-Fr, WITH holidays, 2010-2013')
        warnings.filterwarnings('ignore', module='business_calendar')

    def __init__(self):
        BaseCalendarTest.__init__(self)
        self.holidays = [parse(x) for x in global_holidays.split('\n')]
        self.cal = Calendar(holidays=self.holidays)
        self.cal.warn_on_holiday_exhaustion = False
        rr = rruleset()
        rr.rrule(rrule(DAILY,
                       byweekday=(MO,TU,WE,TH,FR),
                       dtstart=datetime.datetime(2010,1,1)))
        for h in self.holidays:
            rr.exdate(h)
        self.rr = rr
        self.dates = rr.between(datetime.datetime(2010,1,1),
                                datetime.datetime(2013,12,31),
                                inc=True)

    def test_workdaycount_with_non_workday_dates(self):
        print('test_workdaycount_with_non_workday_dates')
        """ Jan 1st is a holiday, Jan 30th and 31st fall on a weekend """
        daycount = 20;
        for date2 in ['Jan 30, 2010','Jan 31, 2010','Feb 1, 2010']:
            count = len(list(self.cal.range('2010-01-01', date2)));
            assert count == daycount
        for date2 in ['Jan 29, 2010','Jan 30, 2010','Jan 31, 2010']:
            count = self.cal.workdaycount('Dec 31, 2009', date2);
            assert count == daycount+1
        for date2 in ['Jan 29, 2010','Jan 30, 2010','Jan 31, 2010']:
            count = self.cal.busdaycount('Dec 31, 2009', date2);
            assert count == daycount
 def __init__(self):
     BaseCalendarTest.__init__(self)
     self.cal = Calendar()
     rr = rruleset()
     rr.rrule(rrule(DAILY,
                    byweekday=(MO,TU,WE,TH,FR),
                    dtstart=datetime.datetime(2010,1,1)))
     self.rr = rr
     self.dates = rr.between(datetime.datetime(2010,1,1),
                             datetime.datetime(2013,12,31),
                             inc=True)
 def test_range(self):
     busdays = [datetime.date(2018, 4, 28)]
     cal = Calendar(busdays=busdays)
     busdays = list(
         cal.range(
             datetime.date(2018, 4, 27),
             datetime.date(2018, 4, 30),
         ))
     assert [
         datetime.date(2018, 4, 27),
         datetime.date(2018, 4, 28),
     ] == busdays
Example #7
0
 def is_trade_day(cls, date, holidays=None):
     """
     判断给定的这个时间是否是交易日(以日记)
     :param date: 需要判断的时间
     :return:
     """
     try:
         holidays = cls.holidays if holidays is None else holidays
         cal = Calendar(workdays=cls.workdays, holidays=holidays)
         flag = cal.isbusday(dt.datetime(date.year, date.month, date.day))
         return flag
     except Exception as e:
         ExceptionInfo(e)
         return False
Example #8
0
 def trade_days(cls, start, end):
     """
     给定两个时间,计算这个时间段内有多少个交易日
     :param start:
     :param end:
     :return:
     """
     try:
         cal = Calendar(workdays=cls.workdays, holidays=cls.holidays)
         days = cal.busdaycount(start, end)
         return days
     except Exception as e:
         ExceptionInfo(e)
         return 0
 def __init__(self):
     BaseCalendarTest.__init__(self)
     self.holidays = [parse(x) for x in global_holidays.split('\n')]
     self.cal = Calendar(holidays=self.holidays)
     self.cal.warn_on_holiday_exhaustion = False
     rr = rruleset()
     rr.rrule(rrule(DAILY,
                    byweekday=(MO,TU,WE,TH,FR),
                    dtstart=datetime.datetime(2010,1,1)))
     for h in self.holidays:
         rr.exdate(h)
     self.rr = rr
     self.dates = rr.between(datetime.datetime(2010,1,1),
                             datetime.datetime(2013,12,31),
                             inc=True)
Example #10
0
 def trade_period(cls, start, days, holidays=None):
     """
     计算某个时间x个交易日后的时间,或之前(days为一个负数)
     :param start:
     :param days:
     :return:
     """
     try:
         holidays = cls.holidays if holidays is None else holidays
         cal = Calendar(workdays=cls.workdays, holidays=holidays)
         end = cal.addbusdays(start, days)
         return end
     except Exception as e:
         ExceptionInfo(e)
         return start
Example #11
0
    def test_multiple_business_days(self):
        business_days = [
            datetime.date(2018, 4, 28),
            datetime.date(2018, 4, 29)
        ]
        holidays = [datetime.date(2018, 4, 23)]
        cal = Calendar(busdays=business_days, holidays=holidays)

        assert cal.busdaycount(
            datetime.date(2018, 4, 27),
            datetime.date(2018, 4, 29),
        ) == 2
        assert cal.busdaycount(
            datetime.date(2018, 4, 22),
            datetime.date(2018, 4, 29),
        ) == 6
Example #12
0
def workdaydic(start, end):
    "start = '2017/03/17', end = '2017/06/02'"
    "返回的工作日含start不含end"
    cal = Calendar()
    daterange = cal.range(start, end)
    L = []
    [L.append(i) for i in map(lambda x: x.strftime("%Y-%m-%d"), daterange)]
    DateDictList = OrderedDict()
    for i in L:
        if DateDictList.has_key(i) is False:
            DateDictList[i] = {}
            DateDictList[i]['Year'] = i.split('-')[0]
            DateDictList[i]['Month'] = i.split('-')[1]
            DateDictList[i]['Day'] = i.split('-')[2]
        else:
            print 'date dic process completed'
    return DateDictList
Example #13
0
def export_report(request):
    """
     Exporting the monthly attendance report has a PDF format.
    """
    try:
        if request.method == "GET":
            cal = Calendar()
            now = datetime.now()
            this_year = now.year
            this_month = now.month
            date1 = datetime(this_year, this_month, 1)
            date2 = cal.addbusdays(date1, monthrange(this_year, this_month)[1])
            nodw = cal.busdaycount(date1, date2)
            all_days = range(1, nodw + 1)
            dict = {}
            for u in User.objects.all():
                c = Attendance.objects.filter(month=now.strftime("%b"),
                                              username=u,
                                              approved_or_not=True)
                l = 0
                for i in c:
                    l = l + calculate_days(i.from_date, i.to_date)
                    print l
                dict[u] = nodw - l
            context = {
                'dict': dict,
                'this_month': now.strftime("%B"),
                'this_year': this_year,
                'nodw': nodw,
            }
            pdf_filename = '{0}.pdf'.format(now.strftime("%B"))
            temp_path = os.path.join(settings.PDF_ROOT, pdf_filename)
            write_pdf('Reports/report.html', context, temp_path)
            with open(temp_path, 'rb') as fh:
                response = HttpResponse(fh.read(),
                                        content_type="application/pdf")
                response[
                    'Content-Disposition'] = 'inline; filename=' + os.path.basename(
                        temp_path)
            return response
    except Exception, e:
        return HttpResponseRedirect('/error/')
Example #14
0
    def test_busdaycount(self):
        busdays = [datetime.date(2018, 4, 28)]
        cal = Calendar(busdays=busdays)

        nbusdays = cal.busdaycount(
            datetime.date(2018, 4, 27),
            datetime.date(2018, 4, 30),
        )
        assert 2 == nbusdays

        nbusdays = cal.busdaycount(
            datetime.date(2018, 4, 27),
            datetime.date(2018, 4, 28),
        )
        assert 1 == nbusdays

        nbusdays = cal.busdaycount(
            datetime.date(2018, 4, 30),
            datetime.date(2018, 4, 27),
        )
        assert -2 == nbusdays

        # time interval after business day
        nbusdays = cal.busdaycount(
            datetime.date(2018, 4, 30),
            datetime.date(2018, 5, 4),
        )
        assert 4 == nbusdays

        nbusdays = cal.busdaycount(
            datetime.date(2018, 5, 4),
            datetime.date(2018, 4, 30),
        )
        assert -4 == nbusdays

        # time interval before business day
        nbusdays = cal.busdaycount(
            datetime.date(2018, 4, 2),
            datetime.date(2018, 4, 6),
        )
        assert 4 == nbusdays

        nbusdays = cal.busdaycount(
            datetime.date(2018, 4, 6),
            datetime.date(2018, 4, 2),
        )
        assert -4 == nbusdays
 def __init__(self):
     BaseCalendarTest.__init__(self)
     self.holidays = [parse(x) for x in global_holidays.split('\n')]
     self.cal = Calendar(workdays=[0], holidays=self.holidays)
     rr = rruleset()
     rr.rrule(
         rrule(DAILY, byweekday=(MO), dtstart=datetime.datetime(2010, 1,
                                                                1)))
     for h in self.holidays:
         rr.exdate(h)
     self.rr = rr
     self.dates = rr.between(datetime.datetime(2010, 1, 1),
                             datetime.datetime(2013, 12, 31),
                             inc=True)
Example #16
0
 def __init__(self):
     self.holidays = dict(
         hworkday=datetime.date(2018, 1, 1),
         hworkday_two=datetime.date(2018, 1, 2),
         hweekend_day=datetime.date(2018, 1, 7),
     )
     self.specdays = dict(
         sholiday=datetime.date(2018, 1, 2),
         sworkday=datetime.date(2018, 1, 5),
         ssaturday=datetime.date(2018, 1, 13),
     )
     self.busdays = [datetime.date(2018, 1, 14)]
     self.cal = Calendar(
         specdays=self.specdays.values(),
         holidays=self.holidays.values(),
         busdays=self.busdays,
     )
     self.cal.warn_on_holiday_exhaustion = False
     self.workdays = [
         datetime.date(2018, 1, i) for i in range(1, 15)
         if self.cal.isworkday(datetime.date(2018, 1, i))
         and not self.cal.isholiday(datetime.date(2018, 1, i))
     ]
Example #17
0
def tglxqsfgz():
    print('\n\n\n     停工留薪期实发工资计算器\n\n')

    # 调用business_calendar模块计算除去周末的工作日天数
    year = int(input('请输入停工留薪期开始年份(数字):\n'))
    month = int(input('请输入停工留薪期开始月份(数字):\n'))
    day1 = int(input('请输入停工留薪期开始日期(数字):\n'))
    day2 = int(input('请输入停工留薪期结束日期(数字):\n'))
    date1 = datetime.datetime(year, month, day1)
    date2 = datetime.datetime(year, month, day2)
    cal = Calendar()
    print('在{date1}至{date2}期间,除去周末的工作日天数为{busdaycount}天\n'.format(
        date1=date1,
        date2=date2,
        busdaycount=cal.busdaycount(date1, date2) + 1))

    # 计算实发工资
    tinggongliuxinqitianshu = int(
        input('请根据以上天数,核实在此期间是否有法定节日,然后输入停工留薪期天数(数字):\n'))
    # 其实可以直接用business_calendar模块排除法定节假日和周末,但是需要事先录入法定节假日
    gongzhi = float(input('请输入该月实发工资(数字):\n'))
    gongzuorigongzhi = tinggongliuxinqitianshu * (gongzhi / 21.75)
    print('\n停工留薪期实发工资(该月工作日部分):{jisuanjieguo}元'.format(
        jisuanjieguo=float('%.2f' % gongzuorigongzhi)))
Example #18
0
def _initialise_cal_obj(workdays, holidays=[]):
    """Function to initialise custom calendar object.

    The return value must be the custom calendr object.

    Parameters
    ----------
    workdays
        List of custom workdays.
    holidays
        List of custom holidays.

    Returns
    -------
    Object
        Custom calendar object.

    """
    obj_cal = Calendar(workdays=workdays, holidays=holidays)
    return obj_cal
    def test_weekend_is_business_day(self):
        busdays = [datetime.date(2018, 4, 28)]
        cal = Calendar(busdays=busdays)

        next_busday = cal.addbusdays(datetime.date(2018, 4, 27), 1)
        assert datetime.date(2018, 4, 28) == next_busday

        next_busday = cal.addbusdays(datetime.date(2018, 4, 27), 2)
        assert datetime.date(2018, 4, 30) == next_busday

        prev_busday = cal.addbusdays(datetime.date(2018, 4, 30), -1)
        assert datetime.date(2018, 4, 28) == prev_busday

        prev_busday = cal.addbusdays(datetime.date(2018, 4, 30), -2)
        assert datetime.date(2018, 4, 27) == prev_busday
Example #20
0
        caseActivityTimeDict[caseName].append(activityInfo["endTime"])
        activityNameIndex = activityNameList.index(activityInfo["activity"])
        caseActivitySequenceDict[caseName].append(activityNameIndex)

        activityTimestamp = int(
            time.mktime(activityInfo["endTime"].timetuple()))
        timeStampAndIdDict[str(activityTimestamp) + "_" + caseName + "_" +
                           activityInfo["activity"]] = {
                               "caseName": caseName,
                               "activityAppearIndex": activityAppearIndex,
                               "activity": activityInfo["activity"]
                           }

caseActivityStartTimeDict = {}
caseActivityEndTimeDict = {}
cal = Calendar()
for caseName, activityTimeList in caseActivityTimeDict.items():
    startTime = activityTimeList[0]
    endTime = activityTimeList[-1]
    caseActivityStartTimeDict[caseName] = []
    caseActivityEndTimeDict[caseName] = []
    for activityTime in activityTimeList:
        startWorkday = cal.workdaycount(startTime.date(), activityTime.date())
        endWorkday = cal.workdaycount(activityTime.date(), endTime.date())
        caseActivityStartTimeDict[caseName].append(startWorkday)
        caseActivityEndTimeDict[caseName].append(endWorkday)
#print(caseActivityStartTimeDict["d0c4a4241daa1d89"])
#print(caseActivityEndTimeDict["d0c4a4241daa1d89"])

sortedTimeStampAndIdList = sorted(timeStampAndIdDict)
#print(sortedTimeStampAndIdList[0:10])
Example #21
0
        Timeoff_list = []  # 如果找不到该员工ID的请教日期列表,则把该员工ID的请教列表设置为空

    for num, city in enumerate(frame.index):
        Country = City_Country.loc[city.strip('"'),
                                   'Work Location Country']  # 找出城市对应的国家
        Holiday = Holiday_Dict[Country]  # 找出国家对应的假日日期列表

        year1, month1, day1 = frame.iloc[num][
            "BadgeDate"]  # year=2016,month=2, day=4
        year2, month2, day2 = frame.iloc[num]["BadgeDate2"]

        date1 = datetime.datetime(year1, month1,
                                  day1)  # 把# year month day 转为为datatime类型
        date2 = datetime.datetime(year2, month2, day2)

        cal0 = Calendar()
        cal1 = Calendar(workdays=[SA, SU])
        cal2 = Calendar(workdays=[MO, TU, WE, TH, FR],
                        holidays=["2010-01-01", "2020-01-01"] + Holiday +
                        Timeoff_list)
        cal3 = Calendar(workdays=[MO, TU, WE, TH, FR, SA, SU],
                        holidays=["2010-01-01", "2020-01-01"] + Holiday)
        cal4 = Calendar(workdays=[MO, TU, WE, TH, FR, SA, SU],
                        holidays=["2010-01-01", "2020-01-01"] + Timeoff_list)

        bsday0 = int(str(date2 - date1).split(" ")[0]) - 1  # 打卡间隔天数

        date2 = date2 + datetime.timedelta(days=-1)  # 减去一天
        bsday1 = cal1.busdaycount(date1, date2)  # 打卡间隔天数的周六日天数
        bsday2 = cal2.busdaycount(date1, date2)  # 打卡间隔存在的休假日天数
        bsday3 = bsday0 - cal3.busdaycount(date1, date2)  # 打卡间隔存在的节假日天数
Example #22
0
    "2019-07-04",  # Independence day
    "2019-09-02",  # Labor day
    "2019-11-28",  # Thanksgiving day
    "2019-12-25",  # Christmas
    ####
    "2020-01-01",  # New Years
    "2020-01-20",  # MLK day
    "2020-02-17",  # Washington's birthday
    "2020-04-10",  # Good Friday
    "2020-05-25",  # Memorial day
    "2020-07-03",  # Independence day
    "2020-09-07",  # Labor day
    "2020-11-26",  # Thanksgiving day
    "2020-12-25",  # Christmas
]
_calendar_ = Calendar(holidays=_holidays_)


class TimeSeries(object):
    """
    a collection of IntervalData objects for a specific ticker symbol
    """

    def __init__(self):
        """
        the ticker symbol this time series belongs to
        """
        self.ticker = ""

        """
        a list of datetime included in this time series (sorted oldest to newest)
from business_calendar import Calendar, MO, TU, WE, TH, FR
import datetime
date1 = datetime.datetime(2013,1,10)

# normal calendar, no holidays
cal = Calendar()
date2 = cal.addbusdays(date1, 25)
print('%s days between %s and %s' % \
    (cal.busdaycount(date1, date2), date1, date2))

# don't work on Fridays? no problem!
cal = Calendar(workdays=[MO,TU,WE,TH])
date2 = cal.addbusdays(date1, 25)
print('%s days between %s and %s' % \
    (cal.busdaycount(date1, date2), date1, date2))

# holiday? no problem!
cal = Calendar(workdays=[MO,TU,WE,TH], holidays=['2013-01-17'])
date2 = cal.addbusdays(date1, 25)
print('%s days between %s and %s' % \
    (cal.busdaycount(date1, date2), date1, date2))
def calc(df, employee_id):
    myDf = df[df['序号'] == employee_id]

    cal = Calendar()
    # TODO 参数外部配置
    date1 = datetime(2019, 7, 1)
    date2 = datetime(2019, 8, 1)

    # 工作日字符串列表
    my_date_key_list = [
        date_time.strftime('%Y-%m-%d')
        for date_time in list(cal.range(date1, date2))
    ]

    # 初始化{工作日:打卡记录}字典
    d = {k: [] for k in my_date_key_list}
    for date_key in my_date_key_list:
        d[date_key].extend(myDf[myDf['日期'] == date_key]['打卡时间'].tolist())

    # 遍历字典判断
    weidaka_date_list = []
    shangban_weidaka_date_list = []
    xiaban_weidaka_date_list = []

    chidao_count = 0
    chidao_date_list = []

    zaotui_count = 0
    zaotui_date_list = []

    jiaban_count = 0
    jiaban_date_list = []

    shangban_time = time(9, 0, 0)
    xiaban_time = time(18, 0, 0)

    jiaban1_time = time(19, 30, 0)
    jiaban2_time = time(21, 30, 0)

    for date_key in my_date_key_list:
        if len(d[date_key]) == 0:
            weidaka_date_list.append(date_key)
        elif len(d[date_key]) == 1:
            value = d[date_key][0]
            if shangban_time >= value or (shangban_time < value
                                          and value < xiaban_time):
                xiaban_weidaka_date_list.append(date_key)
            elif value >= xiaban_time:
                shangban_weidaka_date_list.append(date_key)

                if value >= jiaban1_time and value < jiaban2_time:
                    jiaban_count += 1
                    jiaban_date_list.append(date_key)
                elif value >= jiaban1_time:
                    jiaban_count += 2
                    jiaban_date_list.append(date_key)
        else:
            starttime = d[date_key][0]
            endtime = d[date_key][-1]

            if starttime > shangban_time:
                chidao_count += 1
                chidao_date_list.append(date_key)
            elif endtime < xiaban_time:
                zaotui_count += 1
                zaotui_date_list.append(date_key)

            if endtime >= jiaban1_time and endtime < jiaban2_time:
                jiaban_count += 1
                jiaban_date_list.append(date_key)
            elif endtime >= jiaban1_time:
                jiaban_count += 2
                jiaban_date_list.append(date_key + '*2')

    print("未打卡:", weidaka_date_list)
    print("上班未打卡:", shangban_weidaka_date_list)
    print("下班未打卡:", xiaban_weidaka_date_list)
    print("迟到次数%s,日期:%s:" % (chidao_count, chidao_date_list))
    print("早退次数%s,日期:%s:" % (zaotui_count, zaotui_date_list))

    print("加班次数%s,日期:%s:" % (jiaban_count, jiaban_date_list))
Example #25
0
                      host=Config.REDIS_HOST,
                      port=Config.REDIS_PORT))
prefixed_store = PrefixDecorator('session_', store)
celery = Celery(__name__, broker=Config.CELERY_BROKER_URL)

upload_redis = redis.StrictRedis(db=Config.UPLOAD_REDIS_DB,
                                 host=Config.REDIS_HOST,
                                 port=Config.REDIS_PORT)
email_redis = redis.StrictRedis(db=Config.EMAIL_REDIS_DB,
                                host=Config.REDIS_HOST,
                                port=Config.REDIS_PORT)

holidays = NYCHolidays(
    years=[year for year in range(date.today().year,
                                  date.today().year + 5)])
calendar = Calendar(workdays=[MO, TU, WE, TH, FR],
                    holidays=[str(key) for key in holidays.keys()])


def create_app(config_name, jobs_enabled=True):
    """
    Set up the Flask Application context.

    :param config_name: Configuration for specific application context.

    :return: Flask application
    """

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
 def test_holidays_has_priority(self):
     date = datetime.date(2018, 4, 28)
     busdays = [date]
     holidays = [date]
     cal = Calendar(holidays=holidays, busdays=busdays)
     assert not cal.isbusday(date)
Example #27
0
class Foia(models.Model):
    class Meta:
        verbose_name = 'FOIA'
        verbose_name_plural = 'FOIAs'
        # ordering =

    CALENDAR = 0
    BUSINESS = 1
    reporter = models.ForeignKey(
        MyUser, null=True,
        verbose_name="Who filed this request?")  # many-to-one
    agency = models.ForeignKey(Agency, null=False)

    filed_date = models.DateField('date filed')
    request_subject = models.CharField('what was the request for?',
                                       blank=True,
                                       null=True,
                                       max_length=1000)
    request_notes = models.TextField(
        'Request text and/or notes',
        help_text=
        "Did you send by mail or email? Why did you phrase it the way you did?",
        blank=True)
    is_state_foia = models.BooleanField(
        "Is this a FOIA filed with a state or a foreign country?",
        help_text=
        "This app doesn't know about the FOIA deadlines in those places, so you won't get notifications for these, but you're welcome to track it here.",
        default=False)

    received_ack_letter = models.BooleanField(
        'Have you received an acknowledgement yet?', default=False)
    ack_date = models.DateField('date acknowledgement letter received',
                                blank=True,
                                null=True)
    request_number = models.CharField(max_length=200, blank=True)
    submission_notes = models.TextField(
        'notes about the process',
        blank=True,
        help_text=
        "Record your phone call updates here. Did they respond by mail or email? Do you have a phone number? Did they tell you what track it\'s on?"
    )
    date_response_due_custom = models.DateField(
        "When are the records due? (Custom due date)", blank=True, null=True)

    received_response = models.BooleanField(
        'Have you received responsive docs (or a denial) yet?')
    resp_date = models.DateField('date response received',
                                 blank=True,
                                 null=True)
    response_satisfactory = models.BooleanField(
        "We're satisfied with what we got and do not need to appeal, sue or pursue this any further.",
        default=False)
    response_notes = models.TextField(
        "Notes about your response.",
        help_text="Complain about the redactions here!",
        blank=True)
    response_url = models.TextField(
        "Link to the documents and/or response letter. (Optional. Skip this if you're storing the documents on paper or offline)",
        blank=True,
        help_text=
        "Google Drive and Dropbox are both good places to store documents and both generate shareable links you could paste here."
    )

    appealed = models.BooleanField('Have you (or your lawyer) appealed this?',
                                   default=False)
    appeal_date = models.DateField('date appeal filed', blank=True, null=True)
    lawsuit_filed = models.BooleanField(
        'Have you (or your lawyer) filed a lawsuit over this?', default=False)
    lawsuit_filed_date = models.DateField('date lawsuit filed',
                                          blank=True,
                                          null=True)
    lawsuit_notes = models.TextField("Notes about the lawsuit ", blank=True)

    # I don't want to notify people multiple times a day, ever.
    # so... this keeps track of the day of the most recent notification
    # and only sends if today is after the most recent notification date.
    last_notified = models.DateField('most recent date notified', null=True)

    # a real-life, honest-to-goodness lawyer says:
    #    The response is due 20 business days after receipt of the request (but
    #      the agency can get a 10 business day extension if there exist "unusual circumstances").
    #    The appeal response deadline is also 20 business days after the appeal is received.
    #    The acknowledgment bit is agency by agency (it's done by regulation, generally). A lot
    #      of them have the 10-day requirement, but I'm not sure it's true that they all do.

    ack_due_duration = [10, BUSINESS
                        ]  # 10 business days after sent (for some agencies)
    response_due_duration = [
        20, BUSINESS
    ]  # 20 business days after sent (but there are extensions)
    appeal_almost_due_duration = [
        85, BUSINESS
    ]  # an arbitrary Jeremy-chosen amount less than 90 days after response
    appeal_due_duration = [90, CALENDAR
                           ]  # 90 days (not business, calendar) after response
    appeal_response_due_duration = [20, BUSINESS
                                    ]  # 20 business days after appeal filed

    def __str__(self):
        return "{} FOIA filed on {} by {}".format(self.agency, self.filed_date,
                                                  self.reporter)

    def edit_link(self):
        return Site.objects.get_current().domain + reverse(
            'admin:foias_foia_change', args=[self.id])

    STATUSES = {
        "LITIGATION": {
            "name": "in litigation",
            "sort_order":
            10  # FOIAs in litigation are very boring (everyone who needs to know already knows)
        },
        "APPEALED": {
            "name": "appealed",
            "sort_order": 4
        },
        "RESPONSE_RECEIVED_OK": {
            "name": "response received!",
            "sort_order": 11
        },
        "RESPONSE_RECEIVED_UNAPPEALABLE": {
            "name": "response received (too late to appeal)",
            "sort_order": 5
        },
        "RESPONSE_RECEIVED_NOT_YET_APPEALED": {
            "name": "response received (not yet appealed)",
            "sort_order": 3
        },
        "ACKED": {
            "name": "acknowledged",
            "sort_order": 1
        },
        "FILED": {
            "name": "filed",
            "sort_order": 2
        },
    }

    def sort_order(self):
        """sort order for cases, based on status"""
        # apparently this is the pythonic way to do it!
        # ...
        # c'mon python.
        # these'll be sorted asc by default, so bigger numbers are at the bottom.

        return self.STATUSES[self._status()]["sort_order"]

    def sortable_filed_date(self):
        return self.filed_date.strftime('%s')

    def _status(self):
        if self.lawsuit_filed:
            return "LITIGATION"
        elif self.appealed:
            return "APPEALED"
        elif self.received_response:  # acknowledged, responded to, but not appealed
            if self.response_satisfactory:
                return "RESPONSE_RECEIVED_OK"
            elif self.date_appeal_due() < datetime.date.today():
                return "RESPONSE_RECEIVED_UNAPPEALABLE"
            else:
                return "RESPONSE_RECEIVED_NOT_YET_APPEALED"
        elif self.received_ack_letter:
            return "ACKED"
        else:  # no lawsuit, no appeal, no response, no ack.
            return "FILED"

    def status(self):
        return self.STATUSES[self._status()]["name"]

    def is_incalculable(self):
        """For various reasons, we may not be able to know anything about certain FOIAs -- e.g. if they're filed with a state, not the feds."""
        return self.is_state_foia

    def next_due_date(self):
        if self.lawsuit_filed:
            return "ask Legal Dept."
        if self.response_satisfactory:
            return ""
        elif self.is_incalculable():
            if not self.received_response and self.date_response_due_custom:
                if self.date_response_due() < datetime.date.today():
                    return "Response overdue, was due {}".format(
                        self.date_response_due())
                else:
                    return "Agency owes us a response due {}".format(
                        self.date_response_due())
            else:
                return "Unknown"
        else:
            if self.appealed:
                return "Appeal response due {}".format(
                    self.date_appeal_response_due())
            elif self.received_response:
                if self.date_appeal_due() < datetime.date.today():
                    return "Too late to appeal."
                else:
                    return "Appeal due {}".format(self.date_appeal_due())
            else:  # not appealed and no response received yet
                if (not self.received_ack_letter
                    ) and self.date_ack_due() > datetime.date.today():
                    return "Agency owes us an acknowledgement by {}".format(
                        self.date_ack_due())
                else:
                    if self.date_response_due() < datetime.date.today():
                        return "Response overdue, was due {}".format(
                            self.date_response_due())
                    else:
                        return "Agency owes us a response by {}".format(
                            self.date_response_due())

    def date_ack_due(self):
        if not self.filed_date:
            return "(not yet calculated)"
        return self._calculate_due_date(
            datetime.datetime(*(self.filed_date.timetuple()[:6])),
            *self.ack_due_duration)

    date_ack_due.short_description = 'Date acknowledgment is due (depending on agency)'

    def date_response_due(self):
        if not self.filed_date:
            return None
        if self.date_response_due_custom:
            return self.date_response_due_custom
        if self.is_incalculable():
            return None
        return self._calculate_due_date(
            datetime.datetime(*(self.filed_date.timetuple()[:6])),
            *self.response_due_duration)

    def date_response_due_human(self):
        return self.date_response_due() or "(not yet calculated)"

    date_response_due_human.short_description = mark_safe(
        "When are the records due? (Automatically calculated) <a href='#' id='custom-resp-due'>Set a custom due date</a>"
    )

    def date_appeal_almost_due(self):
        if not self.resp_date:
            return "(unknown)"
        return self._calculate_due_date(
            datetime.datetime(*(self.resp_date.timetuple()[:6])),
            *self.appeal_almost_due_duration)

    def date_appeal_due(self):
        if not self.resp_date:
            return "(90 biz days after documents are received)"
        return self._calculate_due_date(
            datetime.datetime(*(self.resp_date.timetuple()[:6])),
            *self.appeal_due_duration)

    date_appeal_due.short_description = 'Date appeal is due'

    def date_appeal_response_due(self):
        if not self.appeal_date:
            return "(20 days after appeal is filed)"
        return self._calculate_due_date(
            datetime.datetime(*(self.appeal_date.timetuple()[:6])),
            *self.appeal_response_due_duration)

    date_appeal_response_due.short_description = 'Date agency\'s response to appeal is due'

    def _calculate_due_date(self, from_date, day_count, day_type):
        if day_type == self.CALENDAR:
            return (from_date + datetime.timedelta(days=day_count)).date()
        elif day_type == self.BUSINESS:
            return self.cal.addbusdays(from_date, day_count).date()
        else:
            print("UH OH THIS SHOULDN'T EVER HAPPEN LOL")
            assert False

    def check_if_ack_due(self):
        if self.is_incalculable():
            return False
        return not self.received_ack_letter and self.date_ack_due(
        ) == datetime.date.today()

    def check_if_response_due(self):
        """We might conceivably be able to know this for state/foreign FOIAs, unlike the rest."""
        return (not self.received_response) and \
                self.date_response_due() == datetime.date.today()

    def check_if_appeal_almost_due(self):
        if self.is_incalculable():
            return False
        return self.received_response and self.date_appeal_almost_due(
        ) == datetime.date.today()

    def check_if_appeal_due(self):
        if self.is_incalculable():
            return False
        return self.received_response and not self.response_satisfactory and not self.appealed and self.date_appeal_due(
        ) == datetime.date.today()

    def check_if_appeal_response_due(self):
        if self.is_incalculable():
            return False
        return self.appealed and self.date_appeal_response_due(
        ) == datetime.date.today()

    def notify_if_necessary(self):
        # notify max once per day.
        if self.last_notified == datetime.date.today():
            return
        if self.check_if_ack_due():
            self.notify_that_ack_due()
        elif self.check_if_response_due():
            self.notify_that_response_due()
        elif self.check_if_appeal_almost_due():
            self.notify_that_appeal_almost_due()
        elif self.check_if_appeal_due():
            self.notify_that_appeal_due()
        elif self.check_if_appeal_response_due():
            self.notify_that_appeal_response_due()
        else:
            print("checked FOIA #{}, it doesn't need any notifications".format(
                self.pk))
        self.last_notified = datetime.date.today()
        self.save()

    def notify_that_ack_due(self):
        msg = EmailMultiAlternatives(
            subject='the {} might owe you an acknowledgement on your FOIA'.
            format(self.agency),
            body=
            """the {} might owe you an acknowledgement on your FOIA, about '{}'.\n
It's due on {} (for some agencies). \n
if they haven't sent you one, you might want to give them a call.\n
if they have, please update the FOIA Tracker: {}\n
this message sent by the FOIA Lawya app ({}).
        """.format(self.agency, self.request_subject, self.date_ack_due(),
                   self.edit_link(),
                   Site.objects.get_current().domain),
            to=[self.reporter.email],
            cc=[])
        html_content = """<p>the {} might owe you an acknowledgement on your FOIA, about '{}'.</p>
<p>It's due on {} (for some agencies).</p>
<p>if they haven't sent you one, you might want to give them a call.</p>
<p>if they have, please update the <a href="{}">FOIA Tracker</a><p>
<p>this message sent by the <a href="{}">FOIA Lawya app</a>.</p>
        """.format(self.agency, self.request_subject, self.date_ack_due(),
                   self.edit_link(),
                   Site.objects.get_current().domain)
        msg.attach_alternative(html_content, "text/html")
        msg.send(fail_silently=False)

    def notify_that_response_due(self):
        msg = EmailMultiAlternatives(
            subject='the {} owes you a response to your FOIA'.format(
                self.agency),
            body=
            """the {} owes you a response, due {}, to your FOIA about '{}'. \n
If they haven't sent you a response yet, you might want to contact them.\n
if they have, please update the FOIA Tracker: {}\n
this message sent by the FOIA Lawya app ({}).
        """.format(self.agency, self.date_response_due(), self.request_subject,
                   self.edit_link(),
                   Site.objects.get_current().domain),
            to=[self.reporter.email],
            cc=[
                clerk.email
                for clerk in User.objects.filter(SpecialPerson__is_clerk=True)
            ])
        html_content = """<p>the {} owes you a response, due {}, to your FOIA about '{}'.</p>
<p>If they haven't sent you a response yet, you might want to contact them.
</p>
<p>if they have, please update the <a href="{}">FOIA Tracker</a><p>
<p>this message sent by the <a href="{}">FOIA Lawya app</a>.</p>
        """.format(self.agency, self.date_response_due(), self.request_subject,
                   self.edit_link(),
                   Site.objects.get_current().domain)
        msg.attach_alternative(html_content, "text/html")
        msg.send(fail_silently=False)

    def notify_that_appeal_almost_due(self):
        msg = EmailMultiAlternatives(
            subject="a FOIA appeal is due soon for {}'s request of {}".format(
                self.reporter.name, self.agency),
            body=
            """an appeal for {}'s request from {} about '{}' is due {}. For more details, click here: {}.\n
this message sent by the FOIA Lawya app ({}).
        """.format(self.reporter.name, self.agency, self.request_subject,
                   self.appeal_almost_due_date(), self.edit_link(),
                   Site.objects.get_current().domain),
            to=[
                lawyer.email for lawyer in User.objects.filter(
                    SpecialPerson__is_lawyer=True)
            ],
            cc=[self.reporter.email].append([
                clerk.email
                for clerk in User.objects.filter(SpecialPerson__is_clerk=True)
            ]))
        html_content = """<p>an appeal for {}'s request from {} about '{}' is due {}. For more details, <a href="{}">visit the FOIA Tracker</a>.</p>
<p>this message sent by the <a href="{}">FOIA Lawya app</a>.</p>
        """.format(self.reporter.name, self.agency, self.request_subject,
                   self.appeal_almost_due_date(), self.edit_link(),
                   Site.objects.get_current().domain)
        msg.attach_alternative(html_content, "text/html")
        msg.send(fail_silently=False)

    def notify_that_appeal_due(self):
        msg = EmailMultiAlternatives(
            subject="a FOIA appeal is due today for {}'s request of {}".format(
                self.reporter.name, self.agency),
            body=
            """an appeal for {}'s request from {} about '{}' is due today, {}. For more details, click here: {}.\n
this message sent by the FOIA Lawya app ({}).
        """.format(self.reporter.name, self.agency, self.request_subject,
                   self.appeal_almost_due_date(), self.edit_link(),
                   Site.objects.get_current().domain),
            to=[
                lawyer.email for lawyer in User.objects.filter(
                    SpecialPerson__is_lawyer=True)
            ],
            cc=[self.reporter.email] + [
                clerk.email
                for clerk in User.objects.filter(SpecialPerson__is_clerk=True)
            ])
        html_content = """<p>an appeal for {}'s request from {} about '{}' is due today, {}. For more details, click here: <a href="{}">visit the FOIA Tracker</a>.</p>
<p>this message sent by the <a href="{}">FOIA Lawya app</a>.</p>
        """.format(self.reporter.name, self.agency, self.request_subject,
                   self.appeal_almost_due_date(), self.edit_link(),
                   Site.objects.get_current().domain)
        msg.attach_alternative(html_content, "text/html")
        msg.send(fail_silently=False)

    def notify_that_appeal_response_due(self):
        msg = EmailMultiAlternatives(
            subject="a FOIA response is due back today for {}'s request of {}".
            format(self.reporter.name, self.agency),
            body=
            """an appeal for {}'s request from {} about '{}' is due back today, {}. For more details, click here: {}.\n
this message sent by the FOIA Lawya app ({}).
        """.format(self.reporter.name, self.agency, self.request_subject,
                   self.appeal_almost_due_date(), self.edit_link(),
                   Site.objects.get_current().domain),
            to=[
                lawyer.email for lawyer in User.objects.filter(
                    SpecialPerson__is_lawyer=True)
            ],
            cc=[self.reporter.email] + [
                clerk.email
                for clerk in User.objects.filter(SpecialPerson__is_clerk=True)
            ])
        html_content = """<p>an appeal for {}'s request from {} about '{}' is due back today, {}. For more details, click here: <a href="{}">visit the FOIA Tracker</a>.</p>
<p>this message sent by the <a href="{}">FOIA Lawya app</a>.</p>
        """.format(self.reporter.name, self.agency, self.request_subject,
                   self.appeal_almost_due_date(), self.edit_link(),
                   Site.objects.get_current().domain)
        msg.attach_alternative(html_content, "text/html")
        msg.send(fail_silently=False)

    holidays = [
        # https://www.opm.gov/policy-data-oversight/snow-dismissal-procedures/federal-holidays/#url=2017
        "2020-1-1",  # Wednesday,    #  New Year's Day
        "2020-1-20",  # Monday,      #  Birthday of Martin Luther King, Jr.
        "2020-2-17",  # Monday,      #  Washington's Birthday
        "2020-5-25",  # Monday,      #  Memorial Day
        "2020-7-3",  # Friday,       #  Independence Day
        "2020-9-7",  # Monday,       #  Labor Day
        "2020-10-12",  # Monday,     #  Columbus Day
        "2020-11-11",  # Wednesday,  #  Veterans Day
        "2020-11-26",  # Thursday,   #  Thanksgiving Day
        "2020-12-25",  # Friday,     #  Christmas Day
        "2019-1-1",  # Tuesday,             #  New Year's Day
        "2019-1-21",  # Monday,       #  Birthday of Martin Luther King, Jr.
        "2019-2-18",  # Monday,       #*  Washington's Birthday
        "2019-5-27",  # Monday,       #  Memorial Day
        "2019-7-4",  # Thursday,             #  Independence Day
        "2019-9-2",  # Monday,       #   Labor Day
        "2019-10-14",  # Monday,       #  Columbus Day
        "2019-11-11",  # Monday,       #   Veterans Day
        "2019-11-28",  # Thursday,             #   Thanksgiving Day
        "2019-12-25",  # Wednesday,             #  Christmas Day
        "2018-1-1",  # Monday,      #   New Year's Day
        "2018-1-15",  # Monday,      #  Birthday of Martin Luther King, Jr.
        "2018-2-19",  # Monday,      #*  Washington's Birthday
        "2018-5-28",  # Monday,      #  Memorial Day
        "2018-7-4",  # Wednesday,            #   Independence Day
        "2018-9-3",  # Monday,      #   Labor Day
        "2018-10-8",  # Monday,      #   Columbus Day
        "2018-11-12",  # Monday,      #**   Veterans Day
        "2018-11-22",  # Thursday,            #   Thanksgiving Day
        "2018-12-25",  # Tuesday,            #  Christmas Day
        "2017-1-2",  # Monday,      #*  New Year's Day
        "2017-1-16",  # Monday,      #  Birthday of Martin Luther King, Jr.
        "2017-2-20",  # Monday,      #**   Washington's Birthday
        "2017-5-29",  # Monday,      #  Memorial Day
        "2017-7-4",  # Tuesday,      #   Independence Day
        "2017-9-4",  # Monday,      #   Labor Day
        "2017-10-9",  # Monday,      #   Columbus Day
        "2017-11-10",  # Friday,      #***  Veterans Day
        "2017-11-23",  # Thursday,      #   Thanksgiving Day
        "2017-12-25",  # Monday,      #   Christmas Day
    ]
    cal = Calendar(holidays=holidays)
Example #28
0
def project_stat():
    db = fenxi_mysql.dbmysql()
    objectid = ''
    ####今天
    date = datetime.datetime.now().strftime("%Y-%m-%d")
    ##昨天
    date1 = datetime.datetime.now() + datetime.timedelta(days=-1)
    date1 = date1.strftime("%Y-%m-%d")
    ##前天
    date2 = datetime.datetime.now() + datetime.timedelta(days=-2)
    date2 = date2.strftime("%Y-%m-%d")
    ##今天结束日
    date00 = datetime.datetime.now() + datetime.timedelta(days=1)
    date00 = date00.strftime("%Y-%m-%d")
    ##昨天结束日
    date11 = datetime.datetime.now().strftime("%Y-%m-%d")
    ##前天结束日
    date22 = datetime.datetime.now() + datetime.timedelta(days=-1)
    date22 = date22.strftime("%Y-%m-%d")
    #判断是否为工作日,工作日返回true,非工作日返回false
    cal = Calendar()
    if cal.isbusday(date) == True:
        if cal.isbusday(date1) == False or cal.isbusday(date2) == False:
            d1 = 0
            d2 = 0
            while cal.isbusday(date1) == False:
                d1 = d1 + 1
                days1 = -1 - d1
                date1 = datetime.datetime.now() + datetime.timedelta(
                    days=days1)
                date11 = date1 + datetime.timedelta(days=1)
                date1 = date1.strftime("%Y-%m-%d")
                date11 = date11.strftime("%Y-%m-%d")
            while cal.isbusday(date2) == False:
                d2 = d2 + 1
                days2 = -2 - d2
                date2 = datetime.datetime.now() + datetime.timedelta(
                    days=days2)
                date22 = date2 + datetime.timedelta(days=1)
                date2 = date2.strftime("%Y-%m-%d")
                date22 = date22.strftime("%Y-%m-%d")
                if date1 == date2:
                    d2 = d2 + 1
                    days2 = -2 - d2
                    date2 = datetime.datetime.now() + datetime.timedelta(
                        days=days2)
                    date22 = date2 + datetime.timedelta(days=1)
                    date2 = date2.strftime("%Y-%m-%d")
                    date22 = date22.strftime("%Y-%m-%d")

        print date, date1, date2
        print date00, date11, date22

        ##############################################################################
        objectid = db.object_id_sel()
        objectid_cn = len(objectid)
        i = 1
        #        status=1
        for i in range(objectid_cn):
            obid = objectid[i][0]
            #今天bug数
            td = int(db.bug_objectid_sel(obid, date, date00)[0])
            #昨天bug数
            zt = int(db.bug_objectid_sel(obid, date1, date11)[0])
            #前天bug数
            qt = int(db.bug_objectid_sel(obid, date2, date22)[0])
            pro_stat = db.project_stat_sel(obid, '0')
            status = int(pro_stat[0])
            stardate = pro_stat[1]
            ##今天有bug
            if td > 0:
                print obid
                print td, zt, qt
                #项目进行中
                if status == 1:
                    if zt == 0 and qt == 0:
                        total = int(
                            db.bug_objectid_sel(obid, stardate, date2)[0])
                        jk_total = int(
                            db.jenkins_source_sel(obid, stardate, date2)[0])
                        db.project_stat_update(total, jk_total, date2, '1',
                                               obid, '0')
                        print "如果项目进行中,今天无bug,更改项目状态为:结束"

                #项目结束
                if status == 0:
                    bugcn = td - zt
                    if bugcn >= 1:
                        obname = db.object_name_sel(obid)
                        proname = obname[0] + str(date)
                        db.project_stat_save(proname, obid, date, '0')
            #            print obname[0],bugcn
            #今天无bug
            else:
                #项目进行中
                if status == 1:
                    if zt == 0:
                        total = int(
                            db.bug_objectid_sel(obid, stardate, date1)[0])
                        jk_total = int(
                            db.jenkins_source_sel(obid, stardate, date1)[0])
                        db.project_stat_update(total, jk_total, date2, '1',
                                               obid, '0')
                        print "如果项目进行中,今天无bug,更改项目状态为:结束"
                print obid
                print td, zt, qt
from business_calendar import Calendar, MO, TU, WE, TH, FR
import datetime
import calendar

year = 2018
month = 12
businessDayCount = 0
holidayDayCount = 0

monthRange = calendar.monthrange(year,month)
cal = Calendar()

for i in range(1,monthRange[1]+1):
	date1 = datetime.datetime(year,month,i) 
	if cal.isbusday(date1):
		# print('%s   : %s' % (i, "Business Day"))
		businessDayCount +=1
	else:
		# print('%s   : %s' % (i, "Holiday Day"))
		holidayDayCount +=1

print('Year        : %s' % year)
print('Month       : %s' % month)
print('Business Day: %s days' % (businessDayCount))
print('Holiday Day : %s days' % (holidayDayCount))
print('Total Day   : %s days' % (monthRange[1]))
max_accuracy_model = models[max_accuracy_index]

print("The best Model is " + str(max_accuracy_model).split('(')[0])
print("Accuracy: {:.2f}%".format(accuracies[max_accuracy_index] * 100))
print("Start predicting close prices in the following " + str(timeperiod) +
      " days.")

# Re-train the model with whole dataset, and make a prediction for the last n(timeperiod) days.
max_accuracy_model.fit(X, Y)
prediction = max_accuracy_model.predict(real_time_test)

print("=======================================================")

close_prices = real_time_test.close.to_numpy()
days = date_series[-timeperiod:].values.astype("datetime64[D]")
cal = Calendar()

# Stock market does not open during weekends, so we need to add n(timeperiod) business days
# representing the future days
following_days = [cal.addbusdays(str(day), timeperiod) for day in days]

# print out the result
for i in range(timeperiod):
    comparator = ''
    if prediction[i] == 1:
        comparator = '>'
    else:
        comparator = '<'

    print("On {date}, {stock}'s close price would be {comparator} {price}" \
        .format(date=following_days[i].date(),
Example #31
0
def preprocessor(input_file, t, output):
    # (tollgate_id,direction)五个方向 0-(1,0) 1-(1,1) 2-(2,0) 3-(3,0) 4-(3,1)
    # 三维特征  vehicle_mode{0-7}, has_etc{0,1}, vehicle_type{0,1,unknown}
    corr_pair = [[1, 0], [1, 1], [2, 0], [3, 0], [3, 1]]
    time_point = dict()  # 三个维度的各类别
    volume_per_slot = dict()  # 车流量
    working_day = dict()  # 是否工作日
    sample_cnt = 0
    time_interval = t
    output_file = output
    time_slot_cnt = 0
    with open(input_file, 'r') as f:
        f.readline()  # ignore the title
        # 输入前先将数据集递增排序
        for line in f:
            sample = line.split(',')
            time_stamp = datetime.strptime(sample[0], '%d/%m/%Y %H:%M')
            if sample_cnt == 0:
                mins = time_stamp.minute % 10
                if mins == 0:
                    begin_time = time_stamp
                else:
                    begin_time = time_stamp - timedelta(minutes=mins)
            minutes = (time_stamp - begin_time).seconds / 60
            if minutes >= time_interval or sample_cnt == 0:
                # 每隔time_interval 初始化一次
                mins = time_stamp.minute % 10
                if mins == 0:
                    begin_time = time_stamp
                else:
                    begin_time = time_stamp - timedelta(minutes=mins)
                index = datetime.strftime(begin_time, '%d/%m/%Y %H:%M')
                volume_per_slot[index] = [0 for _ in range(5)]
                time_point[index] = [dict() for _ in range(5)]
                for i in range(5):
                    time_point[index][i]['mode'] = [0 for _ in range(8)]
                    time_point[index][i]['etc'] = [0 for _ in range(2)]
                    time_point[index][i]['type'] = [0 for _ in range(3)]
                time_slot_cnt += 1
            for i in range(5):
                if str(corr_pair[i][0]) in sample[1] and str(corr_pair[i][1]) in sample[2]:
                    volume_per_slot[index][i] += 1
                    time_point[index][i]['mode'][int(sample[3])] += 1
                    time_point[index][i]['etc'][int(sample[4])] += 1
                    if '1' in sample[5] or '0' in sample[5]:
                        time_point[index][i]['type'][int(sample[5])] += 1
                    else:
                        time_point[index][i]['type'][2] += 1
                    break
            sample_cnt += 1

    with open(str(time_interval)+u'分钟'+output_file, 'w') as f:
        title_str = '"time_window","gate_dir",'
        for i in range(8):
            title_str += 'vehicle_model[' + str(i) + '],'
        for i in range(2):
            title_str += 'has_etc[' + str(i) + '],'
        for i in range(2):
            title_str += 'vehicle_type[' + str(i) + '],'
        title_str += 'no_type,total_volume,working_day'
        f.write(title_str + '\n')
        cal = Calendar()
        for k in volume_per_slot.keys():
            for j in range(5):
                time1 = datetime.strptime(k, '%d/%m/%Y %H:%M')
                time_formalize1 = datetime.strftime(time1, "%Y-%m-%d %H:%M:%S")
                time2 = time1 + timedelta(minutes=time_interval)
                time_formalize2 = datetime.strftime(time2, "%Y-%m-%d %H:%M:%S")
                f.write('"[%s,%s)",' % (time_formalize1, time_formalize2))
                # gate_dir
                f.write('"%d",' % j)
                for m in range(8):
                    f.write('"%d",' % time_point[k][j]['mode'][m])
                for e in range(2):
                    f.write('"%d",' % time_point[k][j]['etc'][e])
                for t in range(2):
                    f.write('"%d",' % time_point[k][j]['type'][t])
                f.write('"%d",' % time_point[k][j]['type'][2])
                f.write('"%d",' % volume_per_slot[k][j])
                if cal.isbusday(time1):
                    working_day[k] = 1
                else:
                    working_day[k] = 0
                f.write('"%d"\n' % working_day[k])
Example #32
0
def init_calendar():
    return Calendar(holidays=holidays)
Example #33
0
# if (int(dayOfWeek) in range(5)) and int(beginWorkSeconds)>0 and int(endWorkSeconds)<0:
#    return 1
# else:
#    return 0
#
#
#print workDay()
#print (datetime.datetime.now()+datetime.timedelta(days=3)).weekday()

date = datetime.datetime.now().strftime("%Y-%m-%d")
date1 = datetime.datetime.now() + datetime.timedelta(days=-1)
date1 = date1.strftime("%Y-%m-%d")
date2 = datetime.datetime.now() + datetime.timedelta(days=-2)
date2 = date2.strftime("%Y-%m-%d")
#判断是否为工作日,工作日返回true,非工作日返回false
cal = Calendar()
if cal.isbusday(date) == True:
    if cal.isbusday(date2) == False:
        d1 = 0
        d2 = 0
        while cal.isbusday(date1) == False:
            d1 = d1 + 1
            days1 = -1 - d1
            date1 = datetime.datetime.now() + datetime.timedelta(days=days1)
            date1 = date1.strftime("%Y-%m-%d")
        while cal.isbusday(date2) == False:
            d2 = d2 + 1
            days2 = -2 - d2
            date2 = datetime.datetime.now() + datetime.timedelta(days=days2)
            date2 = date2.strftime("%Y-%m-%d")
            if date1 == date2: