Esempio n. 1
0
def test_get_rule_month():
    result = frequencies._get_rule_month('W')
    assert (result == 'DEC')
    result = frequencies._get_rule_month(offsets.Week())
    assert (result == 'DEC')

    result = frequencies._get_rule_month('D')
    assert (result == 'DEC')
    result = frequencies._get_rule_month(offsets.Day())
    assert (result == 'DEC')

    result = frequencies._get_rule_month('Q')
    assert (result == 'DEC')
    result = frequencies._get_rule_month(offsets.QuarterEnd(startingMonth=12))
    print(result == 'DEC')

    result = frequencies._get_rule_month('Q-JAN')
    assert (result == 'JAN')
    result = frequencies._get_rule_month(offsets.QuarterEnd(startingMonth=1))
    assert (result == 'JAN')

    result = frequencies._get_rule_month('A-DEC')
    assert (result == 'DEC')
    result = frequencies._get_rule_month(offsets.YearEnd())
    assert (result == 'DEC')

    result = frequencies._get_rule_month('A-MAY')
    assert (result == 'MAY')
    result = frequencies._get_rule_month(offsets.YearEnd(month=5))
    assert (result == 'MAY')
def test_anchored_shortcuts():
    result = frequencies.to_offset('W')
    expected = frequencies.to_offset('W-SUN')
    assert (result == expected)

    result1 = frequencies.to_offset('Q')
    result2 = frequencies.to_offset('Q-DEC')
    expected = offsets.QuarterEnd(startingMonth=12)
    assert (result1 == expected)
    assert (result2 == expected)

    result1 = frequencies.to_offset('Q-MAY')
    expected = offsets.QuarterEnd(startingMonth=5)
    assert (result1 == expected)
Esempio n. 3
0
def test_anchored_shortcuts():
    result = frequencies.to_offset('W')
    expected = frequencies.to_offset('W-SUN')
    assert (result == expected)

    result1 = frequencies.to_offset('Q')
    result2 = frequencies.to_offset('Q-DEC')
    expected = offsets.QuarterEnd(startingMonth=12)
    assert (result1 == expected)
    assert (result2 == expected)

    result1 = frequencies.to_offset('Q-MAY')
    expected = offsets.QuarterEnd(startingMonth=5)
    assert (result1 == expected)

    result1 = frequencies.to_offset('SM')
    result2 = frequencies.to_offset('SM-15')
    expected = offsets.SemiMonthEnd(day_of_month=15)
    assert (result1 == expected)
    assert (result2 == expected)

    result = frequencies.to_offset('SM-1')
    expected = offsets.SemiMonthEnd(day_of_month=1)
    assert (result == expected)

    result = frequencies.to_offset('SM-27')
    expected = offsets.SemiMonthEnd(day_of_month=27)
    assert (result == expected)

    result = frequencies.to_offset('SMS-2')
    expected = offsets.SemiMonthBegin(day_of_month=2)
    assert (result == expected)

    result = frequencies.to_offset('SMS-27')
    expected = offsets.SemiMonthBegin(day_of_month=27)
    assert (result == expected)

    # ensure invalid cases fail as expected
    invalid_anchors = [
        'SM-0', 'SM-28', 'SM-29', 'SM-FOO', 'BSM', 'SM--1'
        'SMS-1', 'SMS-28', 'SMS-30', 'SMS-BAR', 'BSMS', 'SMS--2'
    ]
    for invalid_anchor in invalid_anchors:
        try:
            frequencies.to_offset(invalid_anchor)
        except ValueError:
            pass
        else:
            raise AssertionError(invalid_anchor)
Esempio n. 4
0
    def get_dates_range(self,
                        scale='auto',
                        start=None,
                        end=None,
                        date_max='2010-01-01'):
        '''
        Returns a list of dates sampled according to the specified parameters.

        :param scale: {'auto', 'maximum', 'daily', 'weekly', 'monthly',
            'quarterly', 'yearly'}
            Scale specifies the sampling intervals.
            'auto' will heuristically choose a scale for quick processing
        :param start: First date that will be included.
        :param end: Last date that will be included
        '''
        if scale not in [
                'auto', 'maximum', 'daily', 'weekly', 'monthly', 'quarterly',
                'yearly'
        ]:
            raise ValueError('Incorrect scale: %s' % scale)
        start = Timestamp(start or self._start.min() or date_max)
        # FIXME: start != start is true for NaN objects... is NaT the same?
        start = Timestamp(date_max) if repr(start) == 'NaT' else start
        end = Timestamp(end
                        or max(Timestamp(self._end.max()), self._start.max()))
        # FIXME: end != end ?
        end = datetime.utcnow() if repr(end) == 'NaT' else end
        start = start if self.check_in_bounds(start) else self._lbound
        end = end if self.check_in_bounds(end) else self._rbound

        if scale == 'auto':
            scale = self._auto_select_scale(start, end)
        if scale == 'maximum':
            start_dts = list(self._start.dropna().values)
            end_dts = list(self._end.dropna().values)
            dts = map(Timestamp, set(start_dts + end_dts))
            dts = filter(
                lambda ts: self.check_in_bounds(ts) and ts >= start and ts <=
                end, dts)
            return dts

        freq = dict(daily='D',
                    weekly='W',
                    monthly='M',
                    quarterly='3M',
                    yearly='12M')
        offset = dict(daily=off.Day(n=0),
                      weekly=off.Week(),
                      monthly=off.MonthEnd(),
                      quarterly=off.QuarterEnd(),
                      yearly=off.YearEnd())
        # for some reason, weekly date range gives one week less:
        end_ = end + off.Week() if scale == 'weekly' else end
        ret = list(pd.date_range(start + offset[scale], end_,
                                 freq=freq[scale]))
        ret = [dt for dt in ret if dt <= end]
        ret = [start] + ret if ret and start < ret[0] else ret
        ret = ret + [end] if ret and end > ret[-1] else ret
        ret = filter(lambda ts: self.check_in_bounds(ts), ret)
        return ret
Esempio n. 5
0
    def get_date_ranges(self, start, end, scale='daily', include_bounds=True):
        '''
        Returns a list of dates sampled according to the specified parameters.

        Parameters
        ----------
        start: str
            First date that will be included.
        end: str
            Last date that will be included
        scale: {'daily', 'weekly', 'monthly', 'quarterly', 'yearly'}
            Scale specifies the sampling intervals.
        include_bounds: boolean
            Include start and end in the result if they are not included yet.
        '''
        if scale not in ['daily', 'weekly', 'monthly', 'quarterly', 'yearly']:
            raise ValueError('Incorrect scale: %s' % scale)
        start = Timestamp(start)
        end = Timestamp(end)
        freq = dict(weekly='W', monthly='M', quarterly='3M', yearly='12M')
        offset = dict(weekly=off.Week(),
                      monthly=off.MonthEnd(),
                      quarterly=off.QuarterEnd(),
                      yearly=off.YearEnd())
        if scale == 'daily':
            ret = pd.date_range(start, end, freq='D')
        else:
            ret = pd.date_range(start + offset[scale], end, freq=freq[scale])
        ret = list(ret)
        if include_bounds:
            if start not in ret:
                ret = [start] + ret
            if end not in ret:
                ret = ret + [end]
        return ret
Esempio n. 6
0
    def test_anchored_shortcuts(self):
        result = frequencies.to_offset('W')
        expected = frequencies.to_offset('W-SUN')
        assert (result == expected)

        result1 = frequencies.to_offset('Q')
        result2 = frequencies.to_offset('Q-DEC')
        expected = offsets.QuarterEnd(startingMonth=12)
        assert (result1 == expected)
        assert (result2 == expected)

        result1 = frequencies.to_offset('Q-MAY')
        expected = offsets.QuarterEnd(startingMonth=5)
        assert (result1 == expected)

        result1 = frequencies.to_offset('SM')
        result2 = frequencies.to_offset('SM-15')
        expected = offsets.SemiMonthEnd(day_of_month=15)
        assert (result1 == expected)
        assert (result2 == expected)

        result = frequencies.to_offset('SM-1')
        expected = offsets.SemiMonthEnd(day_of_month=1)
        assert (result == expected)

        result = frequencies.to_offset('SM-27')
        expected = offsets.SemiMonthEnd(day_of_month=27)
        assert (result == expected)

        result = frequencies.to_offset('SMS-2')
        expected = offsets.SemiMonthBegin(day_of_month=2)
        assert (result == expected)

        result = frequencies.to_offset('SMS-27')
        expected = offsets.SemiMonthBegin(day_of_month=27)
        assert (result == expected)

        # ensure invalid cases fail as expected
        invalid_anchors = ['SM-0', 'SM-28', 'SM-29',
                           'SM-FOO', 'BSM', 'SM--1',
                           'SMS-1', 'SMS-28', 'SMS-30',
                           'SMS-BAR', 'SMS-BYR' 'BSMS',
                           'SMS--2']
        for invalid_anchor in invalid_anchors:
            with tm.assert_raises_regex(ValueError,
                                        'Invalid frequency: '):
                frequencies.to_offset(invalid_anchor)
Esempio n. 7
0
    is_superperiod,
)
from pandas._libs.tslibs.parsing import get_rule_month

from pandas.tseries import offsets


@pytest.mark.parametrize(
    "obj,expected",
    [
        ("W", "DEC"),
        (offsets.Week(), "DEC"),
        ("D", "DEC"),
        (offsets.Day(), "DEC"),
        ("Q", "DEC"),
        (offsets.QuarterEnd(startingMonth=12), "DEC"),
        ("Q-JAN", "JAN"),
        (offsets.QuarterEnd(startingMonth=1), "JAN"),
        ("A-DEC", "DEC"),
        ("Y-DEC", "DEC"),
        (offsets.YearEnd(), "DEC"),
        ("A-MAY", "MAY"),
        ("Y-MAY", "MAY"),
        (offsets.YearEnd(month=5), "MAY"),
    ],
)
def test_get_rule_month(obj, expected):
    result = get_rule_month(obj)
    assert result == expected

Esempio n. 8
0
        (dict(microseconds=1), offsets.Micro(1)),
        (dict(microseconds=0), offsets.Nano(0)),
    ],
)
def test_to_offset_pd_timedelta(kwargs, expected):
    # see gh-9064
    td = Timedelta(**kwargs)
    result = frequencies.to_offset(td)
    assert result == expected


@pytest.mark.parametrize(
    "shortcut,expected",
    [
        ("W", offsets.Week(weekday=6)),
        ("W-SUN", offsets.Week(weekday=6)),
        ("Q", offsets.QuarterEnd(startingMonth=12)),
        ("Q-DEC", offsets.QuarterEnd(startingMonth=12)),
        ("Q-MAY", offsets.QuarterEnd(startingMonth=5)),
        ("SM", offsets.SemiMonthEnd(day_of_month=15)),
        ("SM-15", offsets.SemiMonthEnd(day_of_month=15)),
        ("SM-1", offsets.SemiMonthEnd(day_of_month=1)),
        ("SM-27", offsets.SemiMonthEnd(day_of_month=27)),
        ("SMS-2", offsets.SemiMonthBegin(day_of_month=2)),
        ("SMS-27", offsets.SemiMonthBegin(day_of_month=27)),
    ],
)
def test_anchored_shortcuts(shortcut, expected):
    result = frequencies.to_offset(shortcut)
    assert result == expected
import pytest

from pandas._libs.tslibs.parsing import get_rule_month

from pandas.tseries import offsets


@pytest.mark.parametrize(
    "obj,expected",
    [
        ("W", "DEC"),
        (offsets.Week().freqstr, "DEC"),
        ("D", "DEC"),
        (offsets.Day().freqstr, "DEC"),
        ("Q", "DEC"),
        (offsets.QuarterEnd(startingMonth=12).freqstr, "DEC"),
        ("Q-JAN", "JAN"),
        (offsets.QuarterEnd(startingMonth=1).freqstr, "JAN"),
        ("A-DEC", "DEC"),
        ("Y-DEC", "DEC"),
        (offsets.YearEnd().freqstr, "DEC"),
        ("A-MAY", "MAY"),
        ("Y-MAY", "MAY"),
        (offsets.YearEnd(month=5).freqstr, "MAY"),
    ],
)
def test_get_rule_month(obj, expected):
    result = get_rule_month(obj)
    assert result == expected
Esempio n. 10
0
xt = [dav.index[1]] + [dav[str(i)].index[-1] for i in set(dav.index.year)]
yearly = pd.concat(
    [np.exp(dao["Close"][dav.index] - dao["Close"][dat.index[-1]]), cumreturn],
    axis=1).loc[xt]
yearly = pd.concat([yearly, np.exp(np.log(yearly).diff()) - 1], axis=1)
fig = plt.figure(figsize=(12, 4))
np.exp(dao["Close"][dav.index] - dao["Close"][dat.index[-1]]).plot(
    color="#0000ff", alpha=0.5)
plt.title("Decision in " + yv + ", Period: " + str(period), fontsize=11)
plt.ylabel(yv + " Index")
np.exp((dao["Close"][dav.index] - dao["Close"][dat.index[-1]])[1:] *
       score[:-1]).plot(color="#ff0000", linewidth=0.4)
cumreturn.plot(color="#008800", linewidth=0.5)
for ti in range(2, len(yearly.index)):
    plt.annotate(str(round(100 * yearly.iloc[ti, 2], 1)) + "%",
                 xy=(yearly.index[ti] - tso.QuarterEnd(1), yearly.iloc[ti, 0]),
                 xytext=(yearly.index[ti] - tso.QuarterEnd(1),
                         yearly.iloc[ti - 1, 0]),
                 size=6,
                 color='#0000ff',
                 arrowprops=dict(color='#0000ff', alpha=0.5))
    plt.annotate(str(round(100 * yearly.iloc[ti, 3], 1)) + "%",
                 xy=(yearly.index[ti], yearly.iloc[ti, 1]),
                 xytext=(yearly.index[ti], yearly.iloc[ti - 1, 1]),
                 weight=1000,
                 size=6,
                 color='#008800',
                 arrowprops=dict(color='#00cc00', alpha=0.8))
fig.savefig(yv + "_Period_" + str(period) + ".png", format="png")
print(
    pd.Series([