示例#1
0
    def test_DateAdvanceOutOfBounds(self):
        test_date = Date(2199, 12, 30)
        with self.assertRaises(ValueError):
            _ = test_date + '1w'

        test_date = Date(1901, 1, 1)
        with self.assertRaises(ValueError):
            _ = test_date - '1w'
示例#2
0
 def testScheduleInitializeWithYearly(self):
     start_date = Date(2012, 2, 29)
     end_date = Date(2013, 3, 1)
     tenor = Period('1y')
     cal = Calendar('NullCalendar')
     sch = Schedule(start_date, end_date, tenor, cal)
     expected = [Date(2012, 2, 29), Date(2013, 2, 28), Date(2013, 3, 1)]
     for i in range(sch.size()):
         self.assertEqual(expected[i], sch[i])
示例#3
0
    def testScheduleDeepCopy(self):
        start_date = Date(2013, 3, 31)
        end_date = Date(2013, 6, 30)
        tenor = Period('1m')
        cal = Calendar('NullCalendar')
        sch = Schedule(start_date, end_date, tenor, cal)
        copied_sch = copy.deepcopy(sch)

        self.assertEqual(sch, copied_sch)
示例#4
0
def ensure_pyfin_date(date, date_format='%Y-%m-%d'):
    """
    :param date: str, datetime, 日期
    :param date_format: str, 时间格式
    :return: PyFin.Date object 
    """
    if isinstance(date, Date):
        return date
    elif isinstance(date, str):
        return Date.strptime(date, date_format)
    else:
        return Date.fromDateTime(date)
示例#5
0
def ensure_pyfin_date(date, date_format='%Y-%m-%d'):
    """
    :param date: str, datetime, 日期
    :param date_format: str, 时间格式
    :return: PyFin.Date object 
    """
    if isinstance(date, Date):
        return date
    elif isinstance(date, str):
        return Date.strptime(date, date_format)
    else:
        return Date.fromDateTime(date)
示例#6
0
def map_to_biz_day(date_series, calendar='China.SSE', convention=BizDayConventions.Preceding):
    """
    :param date_series: array-like of datetime.datetime
    :param calendar: str, optional, 日历名称,见PyFin.DateUtilities.Calendar, default='China.SSE'
    :param convention: str, optional, 如果日期为节假日,如何调整成交易日,见PyFin.DateUtilities.Schedule, default = preceding
    :return: pd.Series, datetime.datetime, 交易日列表
    """
    unique_date_list = sorted(set(date_series))
    py_date_list = [Date.fromDateTime(date) for date in unique_date_list]
    py_date_list = [Calendar(calendar).adjustDate(date, convention) for date in py_date_list]
    biz_day_list = [Date.toDateTime(date) for date in py_date_list]
    dict_date_map = dict(zip(unique_date_list, biz_day_list))
    ret = date_series.map(dict_date_map)
    return ret
示例#7
0
    def testCalendarWithDayConvention(self):
        sse_cal = Calendar('China.SSE')

        reference_date = Date(2015, 2, 14)
        test_date = sse_cal.adjustDate(
            reference_date, BizDayConventions.HalfMonthModifiedFollowing)
        self.assertEqual(test_date, Date(2015, 2, 13))

        reference_date = Date(2014, 2, 4)
        test_date = sse_cal.adjustDate(reference_date,
                                       BizDayConventions.ModifiedPreceding)
        self.assertEqual(test_date, Date(2014, 2, 7))

        reference_date = Date(2014, 2, 3)
        test_date = sse_cal.adjustDate(reference_date,
                                       BizDayConventions.Nearest)
        self.assertEqual(test_date, Date(2014, 2, 7))

        reference_date = Date(2014, 2, 2)
        test_date = sse_cal.adjustDate(reference_date,
                                       BizDayConventions.Nearest)
        self.assertEqual(test_date, Date(2014, 1, 30))

        with self.assertRaises(ValueError):
            _ = sse_cal.adjustDate(reference_date, -1)
示例#8
0
    def test_ParseDates(self):
        input_date = "2006-01-15"
        d = Date.strptime(input_date, "%Y-%m-%d")
        flag = d == Date(2006, 1, 15)

        self.assertTrue(flag, "date parsing failed\n"
                              " input date:    {0:s}\n"
                              " parsed:        {1}".format(input_date, d))

        input_date = "12/02/2012"
        d = Date.strptime(input_date, "%m/%d/%Y")
        flag = d == Date(2012, 12, 2)

        self.assertTrue(flag, "date parsing failed\n"
                              " input date:    {0:s}\n"
                              " parsed:        {1}".format(input_date, d))

        d = Date.strptime(input_date, "%d/%m/%Y")
        flag = d == Date(2012, 2, 12)

        self.assertTrue(flag, "date parsing failed\n"
                              " input date:    {0:s}\n"
                              " parsed:        {1}".format(input_date, d))

        input_date = "20011002"
        d = Date.strptime(input_date, "%Y%m%d")
        flag = d == Date(2001, 10, 2)

        self.assertTrue(flag, "date parsing failed\n"
                              " input date:    {0:s}\n"
                              " parsed:        {1}".format(input_date, d))
示例#9
0
class TestInputValidation(TestCase):
    @parameterized.expand([([1, 2, 3], pd.Series([1, 2, 3])),
                           (np.array([1.0, 2.0,
                                      3.0]), pd.Series([1.0, 2.0, 3.0])),
                           (pd.Series([1, 2, 3]), pd.Series([1, 2, 3]))])
    def test_ensure_pd_series(self, data, expected):
        calculated = ensure_pd_series(None, None, data)
        assert_series_equal(calculated, expected)

    @parameterized.expand([('2014-01-02', '%Y-%m-%d', Date(2014, 1, 2)),
                           ('2013/05/02', '%Y/%m/%d', Date(2013, 5, 2)),
                           (Date(2013, 5, 2), '%Y/%m/%d', Date(2013, 5, 2))])
    def test_ensure_pyfin_date(self, data, date_format, expected):
        calculated = ensure_pyfin_date(data, date_format)
        self.assertEqual(calculated, expected)

    @parameterized.expand([(None, None, pd.Series([1, 2,
                                                   3]), np.array([1, 2, 3])),
                           (None, None, pd.DataFrame([[1, 2, 3], [2, 3, 4]]),
                            np.array([[1, 2, 3], [2, 3, 4]])),
                           (None, None, np.array([1, 2,
                                                  3]), np.array([1, 2, 3]))])
    def test_ensure_np_array(self, func, argname, data, expected):
        calculated = ensure_np_array(func, argname, data)
        assert_array_equal(calculated, expected)

    @parameterized.expand([
        (pd.DataFrame([1, 2],
                      index=pd.MultiIndex.from_product(
                          [['2010-01-01', '2010-01-02'], ['001']],
                          names=['trade_date', 'sec'])),
         OutputDataFormat.MULTI_INDEX_DF, INDEX_INDUSTRY_WEIGHT,
         pd.DataFrame([1, 2],
                      index=pd.MultiIndex.from_product(
                          [['2010-01-01', '2010-01-02'], ['001']],
                          names=['trade_date', 'industry_code']))),
        (pd.DataFrame([1, 2],
                      index=pd.Index(['2010-01-01', '2010-01-02'],
                                     name='trade_date')),
         OutputDataFormat.PITVOT_TABLE_DF, INDEX_FACTOR,
         pd.DataFrame([1, 2],
                      index=pd.Index(['2010-01-01', '2010-01-02'],
                                     name='trade_date')))
    ])
    def test_ensure_pd_index_names(self, data, data_format, valid_index,
                                   expected):
        calculated = ensure_pd_index_names(data, data_format, valid_index)
        assert_frame_equal(calculated, expected)
示例#10
0
def get_tiaocang_date(start_date, end_date, freq=FreqType.EOM, calendar='China.SSE', date_format='%Y-%m-%d'):
    """
    :param start_date: str/datetime.datetime, 开始日期
    :param end_date: str/datetime.datetime, 结束日期
    :param freq: str enum, default=EOM, 月度
    :param calendar: str, 日历名称
    :param date_format: str, start_date/end_date 如果是str格式,其格式的日期形式
    :return: list, datetime.datetime
    返回在开始日至结束日之间的调仓日(交易日)
    """
    calendar = calendar
    date_format = date_format
    start_date = ensure_pyfin_date(start_date, date_format)
    end_date = ensure_pyfin_date(end_date, date_format)

    cal = Calendar(calendar)
    tiaocang_date = Schedule(start_date,
                             end_date,
                             Period('1' + freq),
                             cal,
                             BizDayConventions.Unadjusted)

    if freq.upper() == FreqType.EOW:
        tiaocang_date = [Date.nextWeekday(date, Weekdays.Friday) for date in tiaocang_date]
    elif freq.upper() == FreqType.EOM:
        tiaocang_date = [cal.endOfMonth(date) for date in tiaocang_date]
    elif freq.upper() == FreqType.EOY:
        tiaocang_date = [Date(date.year(), 12, 31) for date in tiaocang_date]

    tiaocang_date = [cal.adjustDate(date, BizDayConventions.Preceding).toDateTime() for date in tiaocang_date if
                     start_date <= date <= end_date]

    return sorted(set(tiaocang_date))
示例#11
0
    def testSchedulePickle(self):
        start_date = Date(2013, 3, 31)
        end_date = Date(2013, 6, 30)
        tenor = Period('1m')
        cal = Calendar('NullCalendar')
        sch = Schedule(start_date, end_date, tenor, cal)

        f = tempfile.NamedTemporaryFile('w+b', delete=False)
        pickle.dump(sch, f)
        f.close()

        with open(f.name, 'rb') as f2:
            pickled_sch = pickle.load(f2)
            self.assertEqual(sch, pickled_sch)

        os.unlink(f.name)
示例#12
0
    def testNullCalendar(self):
        cal = Calendar("Null")

        testDate = Date(2015, 1, 1)
        self.assertTrue(cal.isBizDay(testDate))
        self.assertTrue(not cal.isHoliday(testDate))
        self.assertTrue(cal.isWeekEnd(Weekdays.Saturday))
        self.assertTrue(cal.isWeekEnd(Weekdays.Sunday))
        self.assertTrue(not cal.isWeekEnd(Weekdays.Friday))
示例#13
0
def map_to_biz_day(date_series,
                   calendar='China.SSE',
                   convention=BizDayConventions.Preceding):
    """
    :param date_series: array-like of datetime.datetime
    :param calendar: str, optional, 日历名称,见PyFin.DateUtilities.Calendar, default='China.SSE'
    :param convention: str, optional, 如果日期为节假日,如何调整成交易日,见PyFin.DateUtilities.Schedule, default = preceding
    :return: pd.Series, datetime.datetime, 交易日列表
    """
    unique_date_list = sorted(set(date_series))
    py_date_list = [Date.fromDateTime(date) for date in unique_date_list]
    py_date_list = [
        Calendar(calendar).adjustDate(date, convention)
        for date in py_date_list
    ]
    biz_day_list = [Date.toDateTime(date) for date in py_date_list]
    dict_date_map = dict(zip(unique_date_list, biz_day_list))
    ret = date_series.map(dict_date_map)
    return ret
示例#14
0
    def test_IsoDate(self):
        input_date = "2006-01-15"
        date_ = Date.parseISO(input_date)
        flag = date_.dayOfMonth() == 15 and date_.month() == 1 and date_.year() == 2006

        self.assertTrue(flag, "Iso date failed\n"
                              " input date:    {0}\n"
                              " day of month:  {1:d}\n"
                              " month:         {2:d}\n"
                              " year:          {3:d}".format(input_date, date_.dayOfMonth(), date_.month(),
                                                             date_.year()))
示例#15
0
    def test_DatePickle(self):
        benchmark_date = Date(2016, 1, 2)

        f = tempfile.NamedTemporaryFile('w+b', delete=False)
        pickle.dump(benchmark_date, f)
        f.close()

        with open(f.name, 'rb') as f2:
            pickled_date = pickle.load(f2)
            self.assertEqual(benchmark_date, pickled_date)

        os.unlink(f.name)
示例#16
0
def get_tiaocang_date(start_date,
                      end_date,
                      freq=FreqType.EOM,
                      calendar='China.SSE',
                      date_format='%Y-%m-%d'):
    """
    :param start_date: str/datetime.datetime, 开始日期
    :param end_date: str/datetime.datetime, 结束日期
    :param freq: str enum, default=EOM, 月度
    :param calendar: str, 日历名称
    :param date_format: str, start_date/end_date 如果是str格式,其格式的日期形式
    :return: list, datetime.datetime
    返回在开始日至结束日之间的调仓日(交易日)
    """
    calendar = calendar
    date_format = date_format
    start_date = ensure_pyfin_date(start_date, date_format)
    end_date = ensure_pyfin_date(end_date, date_format)

    cal = Calendar(calendar)
    tiaocang_date = Schedule(start_date, end_date, Period('1' + freq), cal,
                             BizDayConventions.Unadjusted)

    if freq.upper() == FreqType.EOW:
        tiaocang_date = [
            Date.nextWeekday(date, Weekdays.Friday) for date in tiaocang_date
        ]
    elif freq.upper() == FreqType.EOM:
        tiaocang_date = [cal.endOfMonth(date) for date in tiaocang_date]
    elif freq.upper() == FreqType.EOY:
        tiaocang_date = [Date(date.year(), 12, 31) for date in tiaocang_date]

    tiaocang_date = [
        cal.adjustDate(date, BizDayConventions.Preceding).toDateTime()
        for date in tiaocang_date if start_date <= date <= end_date
    ]

    return sorted(set(tiaocang_date))
示例#17
0
    def testAdjustDate(self):
        # April 30, 2005 is a working day under IB, but a holiday under SSE
        referenceDate = Date(2005, Months.April, 30)

        sseCal = Calendar('China.SSE')
        ibCal = Calendar('China.IB')

        bizDayConv = BizDayConventions.Unadjusted
        self.assertEqual(sseCal.adjustDate(referenceDate, bizDayConv),
                         referenceDate)
        self.assertEqual(ibCal.adjustDate(referenceDate, bizDayConv),
                         referenceDate)

        bizDayConv = BizDayConventions.Following
        self.assertEqual(sseCal.adjustDate(referenceDate, bizDayConv),
                         Date(2005, Months.May, 9))
        self.assertEqual(ibCal.adjustDate(referenceDate, bizDayConv),
                         Date(2005, Months.April, 30))

        bizDayConv = BizDayConventions.ModifiedFollowing
        self.assertEqual(sseCal.adjustDate(referenceDate, bizDayConv),
                         Date(2005, Months.April, 29))
        self.assertEqual(ibCal.adjustDate(referenceDate, bizDayConv),
                         Date(2005, Months.April, 30))
示例#18
0
    def test_strftime(self):
        input_date = Date(2006, 1, 15)
        d = input_date.strftime("%Y-%m-%d")
        flag = d == "2006-01-15"

        self.assertTrue(flag, "strftime failed\n"
                              " input date:    {0}\n"
                              " expected:        {1}".format(input_date, d))

        input_date = Date(2012, 12, 2)
        d = input_date.strftime("%m/%d/%Y")
        flag = d == "12/02/2012"

        self.assertTrue(flag, "strftime failed\n"
                              " input date:    {0}\n"
                              " expected:        {1}".format(input_date, d))

        input_date = Date(2012, 12, 2)
        d = input_date.strftime("%Y%m%d")
        flag = d == "20121202"

        self.assertTrue(flag, "strftime failed\n"
                              " input date:    {0}\n"
                              " expected:        {1}".format(input_date, d))
示例#19
0
 def testScheduleInitialize(self):
     start_date = Date(2013, 3, 31)
     end_date = Date(2013, 6, 30)
     tenor = Period('1m')
     cal = Calendar('NullCalendar')
     sch = Schedule(start_date, end_date, tenor, cal)
     expected = [
         Date(2013, 3, 31),
         Date(2013, 4, 30),
         Date(2013, 5, 31),
         Date(2013, 6, 30)
     ]
     for i in range(sch.size()):
         self.assertEqual(expected[i], sch[i])
示例#20
0
    def testAdvanceDate(self):
        referenceDate = Date(2014, 1, 31)
        sseCal = Calendar('China.SSE')
        ibCal = Calendar('China.IB')

        bizDayConv = BizDayConventions.Following

        # test null period
        self.assertEqual(
            sseCal.advanceDate(referenceDate, Period('0b'), bizDayConv),
            Date(2014, 2, 7))

        # test negative period
        self.assertEqual(
            sseCal.advanceDate(referenceDate, Period('-5b'), bizDayConv),
            Date(2014, 1, 24))

        # The difference is caused by Feb 8 is SSE holiday but a working day for IB market
        self.assertEqual(
            sseCal.advanceDate(referenceDate, Period('2b'), bizDayConv),
            Date(2014, 2, 10))
        self.assertEqual(
            sseCal.advanceDate(referenceDate, Period('2d'), bizDayConv),
            Date(2014, 2, 7))
        self.assertEqual(
            ibCal.advanceDate(referenceDate, Period('2b'), bizDayConv),
            Date(2014, 2, 8))
        self.assertEqual(
            ibCal.advanceDate(referenceDate, Period('2d'), bizDayConv),
            Date(2014, 2, 7))

        bizDayConv = BizDayConventions.ModifiedFollowing
        # May 31, 2014 is a holiday
        self.assertEqual(
            sseCal.advanceDate(referenceDate, Period('4m'), bizDayConv, True),
            Date(2014, 5, 30))
示例#21
0
 def test_DateInputWithSerialNumber(self):
     serial_number = 45678
     test_date = Date(serial_number=serial_number)
     self.assertEqual(test_date.serialNumber, serial_number)
示例#22
0
    def testDailySchedule(self):
        # Jan 2 and Jan 3 are skipped as New Year holiday
        # Jan 7 is skipped as weekend
        # Jan 8 is adjusted to Jan 9 with following convention
        start_date = Date(2012, 1, 1)
        s = Schedule(start_date, start_date + 7,
                     Period(length=1, units=TimeUnits.Days),
                     Calendar("China.SSE"), BizDayConventions.Preceding)

        expected = [
            Date(2011, 12, 30),
            Date(2012, 1, 4),
            Date(2012, 1, 5),
            Date(2012, 1, 6),
            Date(2012, 1, 9)
        ]
        self.checkDates(s, expected)

        # The schedule should skip Saturday 21st and Sunday 22rd.
        # Previously, it would adjust them to Friday 20th, resulting
        # in three copies of the same date.
        start_date = Date(2012, 1, 17)
        s = Schedule(start_date, start_date + 7,
                     Period(length=1, units=TimeUnits.Days),
                     Calendar('Target'), BizDayConventions.Preceding)
        expected = [
            Date(2012, 1, 17),
            Date(2012, 1, 18),
            Date(2012, 1, 19),
            Date(2012, 1, 20),
            Date(2012, 1, 23),
            Date(2012, 1, 24)
        ]
        self.checkDates(s, expected)
示例#23
0
    def testChinaSSE(self):
        # China Shanghai Securities Exchange holiday list in the year 2014
        expectedHol = [
            Date(2014, 1, 1),
            Date(2014, 1, 31),
            Date(2014, 2, 3),
            Date(2014, 2, 4),
            Date(2014, 2, 5),
            Date(2014, 2, 6),
            Date(2014, 4, 7),
            Date(2014, 5, 1),
            Date(2014, 5, 2),
            Date(2014, 6, 2),
            Date(2014, 9, 8),
            Date(2014, 10, 1),
            Date(2014, 10, 2),
            Date(2014, 10, 3),
            Date(2014, 10, 6),
            Date(2014, 10, 7),
            # China Shanghai Securities Exchange holiday list in the year 2015
            Date(2015, 1, 1),
            Date(2015, 1, 2),
            Date(2015, 2, 18),
            Date(2015, 2, 19),
            Date(2015, 2, 20),
            Date(2015, 2, 23),
            Date(2015, 2, 24),
            Date(2015, 4, 6),
            Date(2015, 5, 1),
            Date(2015, 6, 22),
            Date(2015, 9, 3),
            Date(2015, 9, 4),
            Date(2015, 10, 1),
            Date(2015, 10, 2),
            Date(2015, 10, 5),
            Date(2015, 10, 6),
            Date(2015, 10, 7),
            # China Shanghai Securities Exchange holiday list in the year 2016
            Date(2016, 1, 1),
            Date(2016, 2, 8),
            Date(2016, 2, 9),
            Date(2016, 2, 10),
            Date(2016, 2, 11),
            Date(2016, 2, 12),
            Date(2016, 4, 4),
            Date(2016, 5, 2),
            Date(2016, 6, 9),
            Date(2016, 6, 10),
            Date(2016, 9, 15),
            Date(2016, 9, 16),
            Date(2016, 10, 3),
            Date(2016, 10, 4),
            Date(2016, 10, 5),
            Date(2016, 10, 6),
            Date(2016, 10, 7),
            # China Shanghai Securities Exchange holiday list in the year 2017
            Date(2017, 1, 1),
            Date(2017, 1, 2),
            Date(2017, 1, 27),
            Date(2017, 1, 28),
            Date(2017, 1, 29),
            Date(2017, 1, 30),
            Date(2017, 1, 31),
            Date(2017, 2, 1),
            Date(2017, 2, 2),
            Date(2017, 4, 2),
            Date(2017, 4, 3),
            Date(2017, 4, 4),
            Date(2017, 5, 1),
            Date(2017, 5, 28),
            Date(2017, 5, 29),
            Date(2017, 5, 30),
            Date(2017, 10, 1),
            Date(2017, 10, 2),
            Date(2017, 10, 3),
            Date(2017, 10, 4),
            Date(2017, 10, 5),
            Date(2017, 10, 6),
            Date(2017, 10, 7),
            Date(2017, 10, 8)
        ]

        cal = Calendar('China.SSE')

        for day in expectedHol:
            self.assertEqual(
                cal.isHoliday(day), True,
                "{0} is expected to be a holiday in {1}".format(day, cal))
            self.assertEqual(
                cal.isBizDay(day), False,
                "{0} is expected not to be a working day in {1} ".format(
                    day, cal))
示例#24
0
 def test_DateInputWithSerialNumberAndNotNullYearMonthDay(self):
     serial_number = 45678
     _ = Date(year=2015, serial_number=serial_number)
示例#25
0
    def test_DateDeepCopy(self):
        benchmark_date = Date(2016, 1, 2)
        copied_date = copy.deepcopy(benchmark_date)

        self.assertEqual(benchmark_date, copied_date)
示例#26
0
    def testDatesList(self):

        fromDate = Date(2014, 1, 31)
        toDate = Date(2014, 2, 28)
        sseCal = Calendar('China.SSE')
        ibCal = Calendar('China.IB')

        benchmarkHol = [
            Date(2014, 1, 31),
            Date(2014, 2, 3),
            Date(2014, 2, 4),
            Date(2014, 2, 5),
            Date(2014, 2, 6)
        ]
        sseHolList = sseCal.holDatesList(fromDate, toDate, False)
        self.assertEqual(sseHolList, benchmarkHol)
        ibHolList = ibCal.holDatesList(fromDate, toDate, False)
        self.assertEqual(ibHolList, benchmarkHol)

        sseHolList = sseCal.holDatesList(fromDate, toDate, True)
        benchmarkHol = [
            Date(2014, 1, 31),
            Date(2014, 2, 1),
            Date(2014, 2, 2),
            Date(2014, 2, 3),
            Date(2014, 2, 4),
            Date(2014, 2, 5),
            Date(2014, 2, 6),
            Date(2014, 2, 8),
            Date(2014, 2, 9),
            Date(2014, 2, 15),
            Date(2014, 2, 16),
            Date(2014, 2, 22),
            Date(2014, 2, 23)
        ]
        self.assertEqual(sseHolList, benchmarkHol)
        ibHolList = ibCal.holDatesList(fromDate, toDate, True)
        benchmarkHol = [
            Date(2014, 1, 31),
            Date(2014, 2, 1),
            Date(2014, 2, 2),
            Date(2014, 2, 3),
            Date(2014, 2, 4),
            Date(2014, 2, 5),
            Date(2014, 2, 6),
            Date(2014, 2, 9),
            Date(2014, 2, 15),
            Date(2014, 2, 16),
            Date(2014, 2, 22),
            Date(2014, 2, 23)
        ]
        self.assertEqual(ibHolList, benchmarkHol)

        sseWorkingDayList = sseCal.bizDatesList(fromDate, toDate)
        d = fromDate
        while d <= toDate:
            if sseCal.isBizDay(d):
                self.assertTrue(d in sseWorkingDayList and d not in sseHolList)
            d += 1

        ibWorkingDayList = ibCal.bizDatesList(fromDate, toDate)
        d = fromDate
        while d <= toDate:
            if ibCal.isBizDay(d):
                self.assertTrue(d in ibWorkingDayList and d not in ibHolList)
            d += 1
示例#27
0
    def testBasicFunctions(self):

        testDate = Date(2015, 7, 11)
        cal = Calendar('China.SSE')
        self.assertTrue(cal.isWeekEnd(testDate.weekday()),
                        "{0} is expected to be a weekend".format(testDate))
        testDate = Date(2015, 7, 13)
        self.assertTrue(not cal.isWeekEnd(testDate.weekday()),
                        "{0} is expected not to be a weekend".format(testDate))

        testDate = Date(2015, 5, 29)
        cal = Calendar('China.SSE')
        self.assertTrue(
            cal.isEndOfMonth(testDate),
            "{0} is expected to be a end of month".format(testDate))

        testDate = Date(2015, 5, 1)
        cal = Calendar('China.SSE')
        endOfMonth = cal.endOfMonth(testDate)
        self.assertEqual(
            endOfMonth, Date(2015, 5, 29),
            "The month end of 2015/5 is expected to be {0}".format(
                Date(2015, 5, 29)))

        bizDates1 = cal.bizDaysBetween(Date(2015, 1, 1), Date(2015, 12, 31),
                                       True, False)
        bizDates2 = cal.bizDaysBetween(Date(2015, 12, 31), Date(2015, 1, 1),
                                       False, True)
        self.assertEqual(bizDates1, bizDates2)
示例#28
0
    def test_Consistency(self):
        min_date = Date.minDate().serialNumber + 1
        max_date = Date.maxDate().serialNumber

        dyold = Date.fromExcelSerialNumber(min_date - 1).dayOfYear()
        dold = Date.fromExcelSerialNumber(min_date - 1).dayOfMonth()
        mold = Date.fromExcelSerialNumber(min_date - 1).month()
        yold = Date.fromExcelSerialNumber(min_date - 1).year()
        wdold = Date.fromExcelSerialNumber(min_date - 1).weekday()

        for i in range(min_date, max_date + 1):
            t = Date.fromExcelSerialNumber(i)
            serial = t.serialNumber
            self.assertEqual(serial, i, "inconsistent serial number:\n"
                                        "   original:      {0:d}\n"
                                        "   serial number: {1:d}".format(i, serial))

            dy = t.dayOfYear()
            d = t.dayOfMonth()
            m = t.month()
            y = t.year()
            wd = t.weekday()

            flag = (dy == dyold + 1) or \
                   (dy == 1 and dyold == 365 and not Date.isLeap(yold)) or \
                   (dy == 1 and dyold == 366 and Date.isLeap(yold))

            self.assertTrue(flag, "wrong day of year increment: \n"
                                  "    date: {0}\n"
                                  "    day of year: {1:d}\n"
                                  "    previous:    {2:d}".format(t, dy, dyold))

            dyold = dy

            flag = (d == dold + 1 and m == mold and y == yold) or \
                   (d == 1 and m == mold + 1 and y == yold) or \
                   (d == 1 and m == 1 and y == yold + 1)

            self.assertTrue(flag, "wrong day,month,year increment: \n"
                                  "    date: {0}\n"
                                  "    year,month,day: {1:d}, {2:d}, {3:d}\n"
                                  "    previous:       {4:d}, {5:d}, {6:d}".format(t, y, m, d, yold, mold, dold))
            dold = d
            mold = m
            yold = y

            self.assertTrue(d >= 1, "invalid day of month: \n"
                                    "    date:  {0}\n"
                                    "    day: {1:d}".format(t, d))

            flag = (m == 1 and d <= 31) or \
                   (m == 2 and d <= 28) or \
                   (m == 2 and d == 29 and Date.isLeap(y)) or \
                   (m == 3 and d <= 31) or \
                   (m == 4 and d <= 30) or \
                   (m == 5 and d <= 31) or \
                   (m == 6 and d <= 30) or \
                   (m == 7 and d <= 31) or \
                   (m == 8 and d <= 31) or \
                   (m == 9 and d <= 30) or \
                   (m == 10 and d <= 31) or \
                   (m == 11 and d <= 30) or \
                   (m == 12 and d <= 31)

            self.assertTrue(flag, "invalid day of month: \n"
                                  "    date:  {0}\n"
                                  "    day: {1:d}".format(t, d))

            flag = (wd == (wdold + 1)) or (wd == 1 or wdold == 7)

            self.assertTrue(flag, "invalid weekday: \n"
                                  "    date:  {0}\n"
                                  "    weekday:  {1:d}\n"
                                  "    previous: {2:d}".format(t, wd, wdold))
            wdold = wd

            s = Date(y, m, d)
            serial = s.serialNumber

            self.assertTrue(serial == i, "inconsistent serial number:\n"
                                         "    date:          {0}\n"
                                         "    serial number: {1:d}\n"
                                         "    cloned date:   {2}\n"
                                         "    serial number: {3:d}".format(t, i, s, serial))
示例#29
0
    def testChinaIB(self):

        # China Inter Bank working weekend list in the year 2014
        expectedWorkingWeekEnd = [
            Date(2014, 1, 26),
            Date(2014, 2, 8),
            Date(2014, 5, 4),
            Date(2014, 9, 28),
            Date(2014, 10, 11),
            # China Inter Bank working weekend list in the year 2015
            Date(2015, 1, 4),
            Date(2015, 2, 15),
            Date(2015, 2, 28),
            Date(2015, 9, 6),
            Date(2015, 10, 10),
            # China Inter Bank working weekend list in the year 2016
            Date(2016, 2, 6),
            Date(2016, 2, 14),
            Date(2016, 6, 12),
            Date(2016, 9, 18),
            Date(2016, 10, 8),
            Date(2016, 10, 9),
            # China Inter Bank working weekend list in the year 2017
            Date(2017, 1, 22),
            Date(2017, 2, 4),
            Date(2017, 4, 1),
            Date(2017, 5, 27),
            Date(2017, 9, 30)
        ]

        cal = Calendar('China.IB')

        for day in expectedWorkingWeekEnd:
            self.assertEqual(
                cal.isHoliday(day), False,
                "{0} is not expected to be a holiday in {1}".format(day, cal))
            self.assertEqual(
                cal.isBizDay(day), True,
                "{0} is expected to be a working day in {1} ".format(day, cal))
示例#30
0
    def test_BasicFunctions(self):
        year = 2015
        month = 7
        day = 24
        str_repr = "{0}-{1:02d}-{2:02d}".format(year, month, day)
        inner_repr = "Date({0}, {1}, {2})".format(year, month, day)

        test_date = Date(year, month, day)
        self.assertEqual(str(test_date), str_repr, "date string:\n"
                                                   "expected:   {0:s}\n"
                                                   "calculated: {1:s}".format(str_repr, str(test_date)))

        self.assertEqual(repr(test_date), inner_repr, "date representation:\n"
                                                      "expected:   {0:s}\n"
                                                      "calculated: {1:s}".format(inner_repr, repr(test_date)))

        self.assertEqual(test_date.year(), year, "date year:\n"
                                                 "expected:   {0:d}\n"
                                                 "calculated: {1:d}".format(year, test_date.year()))

        self.assertEqual(test_date.month(), month, "date month:\n"
                                                   "expected:   {0:d}\n"
                                                   "calculated: {1:d}".format(month, test_date.month()))

        self.assertEqual(test_date.dayOfMonth(), day, "date day:\n"
                                                      "expected:   {0:d}\n"
                                                      "calculated: {1:d}".format(day, test_date.dayOfMonth()))

        self.assertEqual(test_date.dayOfYear(), test_date - Date(2015, 1, 1) + 1, "date day:\n"
                                                                                  "expected:   {0:d}\n"
                                                                                  "calculated: {1:d}"
                         .format(test_date - Date(2015, 1, 1) + 1, test_date.dayOfYear()))
        self.assertEqual(test_date.weekday(), 6, "date weekday:\n"
                                                 "expected:   {0:d}\n"
                                                 "calculated: {1:d}".format(5, test_date.weekday()))

        self.assertEqual(test_date.toDateTime(), dt.datetime(year, month, day), "date datetime representation\n"
                                                                                "expected:   {0}\n"
                                                                                "calculated: {1}".format(
            dt.datetime(year, month, day), test_date.toDateTime()))

        serial_number = test_date.serialNumber
        serial_date = Date(serial_number=serial_number)

        self.assertEqual(serial_date, test_date, "date excel serial number representation\n"
                                                 "expected:   {0:d}"
                                                 "calculated: {1:d}".format(serial_date.serialNumber,
                                                                            test_date.serialNumber))

        # test comparisons
        previous_date = test_date - 1
        self.assertTrue(previous_date < test_date, "{0} is not earlier than {1}".format(previous_date, test_date))
        self.assertFalse(previous_date >= test_date,
                         "{0} should not be later than or equal to {1}".format(previous_date, test_date))
        self.assertTrue((previous_date + 1) == test_date,
                        "{0} plus one day should be equal to {1}".format(previous_date, test_date))

        # check static members
        self.assertEqual(Date.minDate(), Date(1901, 1, 1), "min date is wrong")
        self.assertEqual(Date.maxDate(), Date(2199, 12, 31), "max date is wrong")
        self.assertEqual(Date.endOfMonth(test_date), Date(year, month, 31), "end of month is wrong")
        self.assertTrue(Date.isEndOfMonth(Date(year, month, 31)), "{0} should be the end of month")
        self.assertEqual(Date.nextWeekday(test_date, test_date.weekday()), test_date,
                         "{0}'s next same week day should be {1}"
                         .format(test_date, test_date))
        expected_date = dt.date.today()
        expected_date = dt.datetime(expected_date.year, expected_date.month, expected_date.day)
        self.assertEqual(Date.todaysDate().toDateTime(), expected_date, "today's date\n"
                                                                        "expected:   {0}\n"
                                                                        "calculated: {1}".format(expected_date,
                                                                                                 Date.todaysDate()))

        # nth-week day
        with self.assertRaises(ValueError):
            _ = Date.nthWeekday(0, Weekdays.Friday, 1, 2015)

        with self.assertRaises(ValueError):
            _ = Date.nthWeekday(6, Weekdays.Friday, 1, 2015)

        self.assertEqual(Date.nthWeekday(3, Weekdays.Wednesday, 8, 2015), Date(2015, 8, 19))

        # check plus/sub

        three_weeks_after = test_date + '3W'
        expected_date = test_date + 21
        self.assertEqual(three_weeks_after, expected_date, "date + 3w period\n"
                                                           "expected:   {0}\n"
                                                           "calculated: {1}".format(expected_date, three_weeks_after))

        three_months_before = test_date - "3M"
        expected_date = Date(year, month - 3, day)
        self.assertEqual(three_months_before, expected_date, "date - 3m period\n"
                                                             "expected:   {0}\n"
                                                             "calculated: {1}".format(expected_date,
                                                                                      three_months_before))

        three_months_before = test_date - Period("3M")
        expected_date = Date(year, month - 3, day)
        self.assertEqual(three_months_before, expected_date, "date - 3m period\n"
                                                             "expected:   {0}\n"
                                                             "calculated: {1}".format(expected_date,
                                                                                      three_months_before))

        three_months_after = test_date + "3m"
        expected_date = Date(year, month + 3, day)
        self.assertEqual(three_months_after, expected_date, "date + 3m period\n"
                                                            "expected:   {0}\n"
                                                            "calculated: {1}".format(expected_date, three_months_after))

        one_year_and_two_months_before = test_date - "14m"
        expected_date = Date(year - 1, month - 2, day)
        self.assertEqual(one_year_and_two_months_before, expected_date, "date - 14m period\n"
                                                                        "expected:   {0}\n"
                                                                        "calculated: {1}".format(expected_date,
                                                                                                 three_months_before))

        one_year_and_two_months_before = test_date + "14m"
        expected_date = Date(year + 1, month + 2, day)
        self.assertEqual(one_year_and_two_months_before, expected_date, "date + 14m period\n"
                                                                        "expected:   {0}\n"
                                                                        "calculated: {1}".format(expected_date,
                                                                                                 three_months_before))

        five_months_after = test_date + "5m"
        expected_date = Date(year, month + 5, day)
        self.assertEqual(five_months_after, expected_date, "date + 5m period\n"
                                                           "expected:   {0}\n"
                                                           "calculated: {1}".format(expected_date, five_months_after))
示例#31
0
 def test_DateInputWithoutCompleteInformationOnYearMonthDay(self):
     year = 2015
     month = None
     day = 18
     with self.assertRaises(ValueError):
         _ = Date(year=year, month=month, day=day)