Example #1
0
def get_pos_adj_date(start_date,
                     end_date,
                     formats="%Y-%m-%d",
                     calendar='China.SSE',
                     freq='m'):
    """
    :param start_date: str/datetime.datetime, start date of strategy
    :param end_date: str/datetime.datetime, end date of strat egy
    :param formats: optional, formats of the string date
    :param calendar: str, optional, name of the calendar to use in dates math
    :param freq: str, optional, the frequency of data
    :return: list of datetime.datetime, pos adjust dates
    """
    if isinstance(start_date, str) and isinstance(end_date, str):
        d_start_date = Date.strptime(start_date, formats)
        d_end_date = Date.strptime(end_date, formats)
    elif isinstance(start_date, datetime.datetime) and isinstance(
            end_date, datetime.datetime):
        d_start_date = Date.fromDateTime(start_date)
        d_end_date = Date.fromDateTime(end_date)

    cal = Calendar(calendar)
    pos_adjust_date = Schedule(d_start_date, d_end_date,
                               Period(length=1, units=_freqDict[freq]), cal,
                               BizDayConventions.Unadjusted)
    # it fails if setting dStartDate to be first adjustment date, then use Schedule to compute the others
    # so i first compute dates list in each period, then compute the last date of each period
    # last day of that period(month) is the pos adjustment date
    if _freqDict[freq] == TimeUnits.Weeks:
        pos_adjust_date = [
            Date.toDateTime(Date.nextWeekday(date, Weekdays.Friday))
            for date in pos_adjust_date[:-1]
        ]
    elif _freqDict[freq] == TimeUnits.Months:
        pos_adjust_date = [
            Date.toDateTime(cal.endOfMonth(date))
            for date in pos_adjust_date[:-1]
        ]
    elif _freqDict[freq] == TimeUnits.Years:
        pos_adjust_date = [
            Date.toDateTime(Date(date.year(), 12, 31))
            for date in pos_adjust_date[:-1]
        ]

    pos_adjust_date = [
        date for date in pos_adjust_date if date <= d_end_date.toDateTime()
    ]
    return pos_adjust_date
def date_stamps(start_date, end_date):
    start_date = Date.fromDateTime(start_date)
    end_date = Date.fromDateTime(end_date)

    start_year = start_date.year()
    start_month = start_date.month()

    if start_month <= 3:
        start_month = 3
    elif start_month <= 6:
        start_month = 6
    elif start_month <= 9:
        start_month = 9
    else:
        start_month = 12

    stamps = []

    start_point = Date(start_year, start_month, 1)
    start_point = Date.endOfMonth(start_point)

    while start_point <= end_date:
        stamps.append(start_point.toDateTime().strftime('%Y%m%d'))
        start_point = Date.endOfMonth(start_point + '3m')

    return stamps
Example #3
0
def map_to_biz_day(date_series,
                   calendar='China.SSE',
                   convention=BizDayConventions.Preceding):
    """
    :param date_series: pd.Sereis, datetime.datetime
    :param calendar: str, optional, name of the calendar to use in dates math
    :param convention: str, optional, pyFin date conventions
    :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
    def testBasicFunctions(self):
        year = 2015
        month = 7
        day = 24
        strRepr = "{0}-{1:02d}-{2:02d}".format(year, month, day)
        innerRepr = "Date({0}, {1}, {2})".format(year, month, day)

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

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

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

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

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

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

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

        serialNumber = testDate.serialNumber
        serialDate = Date(serialNumber=serialNumber)

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

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

        # 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(testDate), 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(testDate, testDate.weekday()), testDate,
            "{0}'s next same week day should be {1}".format(
                testDate, testDate))
        expectedDate = dt.date.today()
        expectedDate = dt.datetime(expectedDate.year, expectedDate.month,
                                   expectedDate.day)
        self.assertEqual(
            Date.todaysDate().toDateTime(), expectedDate, "today's date\n"
            "expected:   {0}\n"
            "calculated: {1}".format(expectedDate, 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

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

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

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

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

        oneYearAndTwoMonthsBefore = testDate - "14m"
        expectedDate = Date(year - 1, month - 2, day)
        self.assertEqual(
            oneYearAndTwoMonthsBefore, expectedDate, "date - 14m period\n"
            "expected:   {0}\n"
            "calculated: {1}".format(expectedDate, threeMonthsBefore))

        oneYearAndTwoMonthsBefore = testDate + "14m"
        expectedDate = Date(year + 1, month + 2, day)
        self.assertEqual(
            oneYearAndTwoMonthsBefore, expectedDate, "date + 14m period\n"
            "expected:   {0}\n"
            "calculated: {1}".format(expectedDate, threeMonthsBefore))

        fiveMonthsAfter = testDate + "5m"
        expectedDate = Date(year, month + 5, day)
        self.assertEqual(
            fiveMonthsAfter, expectedDate, "date + 5m period\n"
            "expected:   {0}\n"
            "calculated: {1}".format(expectedDate, fiveMonthsAfter))
Example #5
0
    def testBasicFunctions(self):
        year = 2015
        month = 7
        day = 24
        strRepr = "{0}-{1:02d}-{2:02d}".format(year, month, day)
        innerRepr = "Date({0}, {1}, {2})".format(year, month, day)

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

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

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

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

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

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

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

        serialNumber = testDate.serialNumber
        serialDate = Date(serialNumber=serialNumber)

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

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

        # 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(testDate), 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(testDate, testDate.weekday()), testDate,
                         "{0}'s next same week day should be {1}"
                         .format(testDate, testDate))
        self.assertEqual(Date.todaysDate().toDateTime(), dt.date.today(), "today's date\n"
                                                                          "expected:   {0}\n"
                                                                          "calculated: {1}".format(dt.date.today(),
                                                                                                   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

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

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

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

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

        oneYearAndTwoMonthsBefore = testDate - "14m"
        expectedDate = Date(year - 1, month - 2, day)
        self.assertEqual(oneYearAndTwoMonthsBefore, expectedDate, "date - 14m period\n"
                                                                  "expected:   {0}\n"
                                                                  "calculated: {1}".format(expectedDate,
                                                                                           threeMonthsBefore))

        oneYearAndTwoMonthsBefore = testDate + "14m"
        expectedDate = Date(year + 1, month + 2, day)
        self.assertEqual(oneYearAndTwoMonthsBefore, expectedDate, "date + 14m period\n"
                                                                  "expected:   {0}\n"
                                                                  "calculated: {1}".format(expectedDate,
                                                                                           threeMonthsBefore))

        fiveMonthsAfter = testDate + "5m"
        expectedDate = Date(year, month + 5, day)
        self.assertEqual(fiveMonthsAfter, expectedDate, "date + 5m period\n"
                                                        "expected:   {0}\n"
                                                        "calculated: {1}".format(expectedDate, fiveMonthsAfter))